使用
o
n
、
on、
on、emit实现兄弟组件间的传值
$off使用方式见子组件 a.vue
1、创建一个js文件,比如bus.js
import Vue from 'Vue'
export default new Vue
2、父组件
<template>
<div class="hello">
<aaa></aaa>
<bbb></bbb>
</div>
</template>
<script>
import aaa from "./a";
import bbb from "./b";
export default {
name: "HelloWorld",
data() {
return {
msg:''
};
},
components: {
aaa,
bbb,
},
methods: {},
mounted() {},
};
</script>
<style lang="less" scoped>
</style>
3、创建两个子组件a.vue与b.vue
a.vue
<template>
<div>
{{ msg }}
<button @click="fn">点击传值</button>
<button @click="remove">移除事件</button>
</div>
</template>
<script>
import bus from "../commonjs/bus";
export default {
name: "",
data() {
return {
msg: "(我是a组件的值)",
};
},
components: {},
methods: {
fn() {
bus.$emit("aMsg", this.msg);
bus.$emit("aMsg2", "第二个事件");
},
remove() {
/*
bus.$off()为清除bus上绑定的事件
如果不写参数,则默认为清除所有事件
*/
//多个事件为数组,单个事件为字符串
// bus.$off('aMsg2')
bus.$off(["aMsg2", "aMsg"]);
},
},
};
</script>
<style scoped>
</style>
b.vue
<template>
<div>
<p>{{ msg }}</p>
<p>{{ msg2 }}</p>
</div>
</template>
<script>
import bus from "../commonjs/bus";
export default {
name: "",
data() {
return {
msg: "",
msg2: "",
};
},
components: {},
methods: {
},
mounted() {
bus.$on("aMsg", (data) => {
this.msg = data;
});
bus.$on("aMsg2", (data) => {
this.msg2 = data;
});
},
};
</script>
<style scoped>
</style>