一、绑定事件:
定义:子给父传递数据:通过父组件给子组件绑定一个自定义事件。
@或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,只执行一次。
二、事件解绑:
解绑一个事件
this.$off(‘xxxx’ ) xxxx:事件名称
解绑多个事件
this.$off([‘x1’,’x2’]) 使用数组的形式。
解绑所有事件
this.$off()
销毁组件实例
this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。
案例
App.vue
<template>
<div >
<h1>班级信息:{{title}}</h1>
<hr/>
<!-- @click.native 原生js事件 @click.native="show"-->
<Person @getName="showName" ref="person" />
</div>
</template>
<script>
import Person from './components/Person.vue';
export default {
name:"App",
data(){
return {
title:"2209班",
}
},
methods: {
showName(name) {
console.log("App得到了姓名",name);
},
showAge(age){
console.log("App得到了年龄(this.refs.xxx.$on)",age);
},
show(){
alert("123")
}
},
components: {
Person
},
mounted(){
//第一个参数:自定义事件的名称,第二个参数:自定义事件的回调
//$once 事件只执行一次
this.$refs.person.$on("getAge",this.showAge);
}
}
</script>
<style>
</style>
components-Person
<template>
<div>
姓名:{{name}},年龄:{{age}}
<button @click="sendName">发送信息给父组件</button>
<button @click="sendAge">发送年龄给父组件</button>
<button @click="offAge">解绑年龄</button>
<button @click="mydestory">销毁组件实例</button>
</div>
</template>
<script>
export default{
name:"Person",
data(){
return {
name:"张三",
age:19
}
},
methods:{
sendName(){
// console.log("子组件",this.name);
this.$emit("getName",this.name);
},
sendAge(){
this.$emit("getAge",this.age);
},
offAge(){
console.log("getAge 已解绑")
this.$off("getAge");
},
// 销毁组件实例
mydestory(){
console.log("组件实例已销毁");
this.$destroy();
}
}
}
</script>
<style>
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')