使用bus事件中心(空的vue对象;
方便起见:
新建文件bus.js文件
import Vue from 'Vue';
export default new Vue();
兄弟组件1
<template>
<div>
<button @click="sendmsgToMyBrother">向我兄弟传值</button>
</div>
</template>
<script>
// 引入bus事件
import bus from '../bus';
export default {
name: 'child'
data () {
return {};
}
},
mounted () {
// console.log(props);
},
methods: {
sendmsgToMyBrother () {
bus.$emit('toChangeMsgToMy', '自家兄弟别这样');
}
}
};
兄弟组件2
<template>
<div>子组件2
<p>dsada{{msg}}</p>
</div>
</template>
<script>
// 引入bus事件
import bus from '../bus';
export default {
name: 'child1',
data () {
return {
msg: ''
};
},
mounted () {
bus.$on('toChangeMsgToMy', (val) => {
this.msg = val;
console.log(val);
});
}
};
</script>