1.在test.vue中引入A和B组建
<style lang="scss" scoped>
div {
padding: 10px;
margin-top: 10px;
line-height: 1.3;
box-sizing: border-box;
}
</style>
<template>
<div>
<A></A>
<B></B>
</div>
</template>
<script>
import A from '@/components/A.vue'
import B from '@/components/B.vue'
export default {
components: {
A,
B
},
data() {
return {
};
},
};
</script>
2.在A组件中创建自定义printa事件
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.a {
}
</style>
<template>
<div class="a">
<button @click="emita">a</button>
</div>
</template>
<script>
import event from '@/assets/js/event.js';
export default {
props: {
},
data() {
return {
}
},
created() {
},
methods:{
emita(){
event.$emit('printa','a')
}
}
}
</script>
3.在B组件中接收并触发printa事件
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.b {
}
</style>
<template>
<div class="b">
b
</div>
</template>
<script>
import event from '@/assets/js/event.js';
export default {
props: {
},
data() {
return {
}
},
mounted() {
event.$off('printa') // 阻止printa事件被触发多次
event.$on('printa',this.print) // 绑定
},
methods:{
print(val){
console.log('val',val);
}
},
beforeDestroy() {
console.log('beforeDestroy print');
event.$off('printa',this.print) // 记得要及时解绑,否则可能会造成内存泄漏
}
}
</script>
为了防止自定义事件被触发多次,记得在
o
n
之
前
先
执
行
on之前先执行
on之前先执行off
4.event.js中的代码:
import Vue from 'vue'
export default new Vue()