组件通信:子组件 => 父组件
1.基础方法
父组件向子组件传函数,子组件通过调用函数实现传入。
2.方法二
在父组件中给子组件绑定一个自定义事件
- 第一种方式:
在父组件中:<Student v-on:aaa="getStudentlName"></Student>
例如:
父组件中:
<Student v-on:aaa="getStudentlName"></Student>
<script>
getStudentlName(name){
console.log('App收到了学生名:',name)
}
</script>
子组件中:
<button @click="sendStudentName">把学生名给App</button>
<script>
sendStudentName(){
//触发student组件实例身上的aaa事件
this.$emit('aaa',this.name)
}
</script>
- 第二种方式:
在父组件中:<Student ref="student" />
例如:
父组件中:
<Student ref="student" />
<script>
mounted(){
this.$refs.student.$on('aaa',this.getStudentlName)
}
</script>
子组件与方式一相同
注 :通过this.$refs.student.$on('aaa',回调函数)
绑定自定义事件时,回调函数 要么配置在methods中直接使用,要么使用箭头函数放入,否则this指向出现问题。
另:解绑自定义事件
this.$off('aaa')
this.$off(['aaa','bbb'])
this.$off()
注:组件上也可以绑定原生DOM事件,需要使用native
修饰符