组件自定义事件可以实现,子组件给父组件传递数据
给子组件绑定事件
vue
<template>
<div>
<Student ref="MyStudent"></Student>
</div>
</template>javascript
mounted() {
// 此处若是箭头函数this则是当前组件实例对象
this.$refs.MyStudent.$on("atguigu", (value) => {
console.log(value);
this.name = value;
});
},子组件绑定触发事件
vue
<button @click="sendStudentName">传递学生名给APP</button>vue
methods:{
sendStudentName(){
this.$emit('atguigu',this.name)
},
unbind(){
this.$off("atguigu") //解绑一个自定义事件
// this.$off(["atguigu","m1"]) //解绑多个自定义事件
// this.$off() //解绑所有的自定义事件
}
}