基本用法

父组件注册了一个事件。如 change 事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<template>
<view class="">
<text>父组件+{{fatherVal}}</text>
<son @change="getSonVal"></son>
</view>
</template>
<script>
import son from '@/components/son.vue'
export default {
components: {
son
},
data(){
return{
fatherVal:''
}
},
methods: {
getSonVal(e) {
console.log(e)
this.fatherVal = e
...
}
}
}
</script>

该事件函数 getSonVal() 执行是要等子组件调用 this.$emit 后执行;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
<view class="">
<text>子组件</text>
<input value="sonVal" @input="valChange" />
</view>
</template>
<script>
export default {
name: 'son',
data(){
return{
sonVal:'子组件数据'
}
},
methods: {
valChange() {
this.$emit('change',this.sonVal)
...
}
}
}
</script>

父组件的函数理解成一个回调函数;

子组件执行函数后将参数返回给父组件,父组件再执行函数。