绑定事件
定义:子组件给父组件传递数据:通过父组件给予组件绑定一个自定义事件。
@ 或 v-on
App.vue 代码:
<Student @sendName="getName"/> <!--Student是子组件,sendName:事件名称,getName:回调函数-->
Student.vue代码:
使用this.$emit调用,第一个参数为:事件名称,第二个参数:传递的数据
methods: { pressBtn() { // 调用自定义事件 this.$emit('sendName',this.name); } },
子组件添加 ref
给子组件添加 ref="student",用 $on 的方式添加,第一个参数:名称,第二个参数回调函数
mounted() {
this.$refs.student.$on("sendName",this.getName);
}
注意:
1、如果子组件调用原生事件 需要添加 native,否则会当成自定义组件,如:
@click.native = "show"
2、$once 只执行一次。