組件自定義事件 事件解綁 組件銷毀
組件標簽上綁定事件,相當於給vc綁定自定義事件,此時用$emit觸發.
組件內元素上綁定事件,事件的回調可以寫在methods里面
子傳父
- v-on|once + $emit
- mounted + ref + $emit
案例
App.vue
<template>
<div id="app">
<CustomChild @CustomEvent="getCustom" />
<CustomChild ref="child" />
</div>
</template>
<script>
import CustomChild from "./components/CustomChild.vue";
export default {
name: "App",
components: {
CustomChild,
},
methods: {
getCustom(payload) {
console.log("getCustom: ", payload);
},
},
mounted() {
const _this = this.$refs.child;
this.$refs.child.$on("CustomEvent2", function (payload) {
console.log("getCustom2: ", payload);
console.log(this === _this); // true 一般情況下this指向事件綁定的組件實例,而不是當前組件實例。 可以使用箭頭函數
});
},
};
</script>
CustomChild.vue
<template>
<button @click="emitSup">子傳父</button>
</template>
<script>
export default {
data: () => ({
payload:{
msg:'data from child'
}
}),
methods:{
emitSup(){
this.$emit('CustomEvent',this.payload)
this.$emit('CustomEvent2',this.payload)
}
}
};
</script>
<style>
h1 {
color: salmon;
}
</style>
組件銷毀與自定義事件解綁
解綁事件
this.$off('e')
this.$off(['e','e1'])
this.$off() // 所有自定義事件
銷毀組件實例
this.$destory 組件銷毀后,自定義事件全部失效