兄弟间通信:
场景:点击子组件一更改子组件二的内容
bus.js:
import Vue from 'vue'
export default new Vue;
父组件:
<template>
<div id="app">
<my-page />
<my-page-two />
</div>
</template>
<script>
import myPage from './components/myPage.vue'
import myPageTwo from './components/myPage1.vue'
export default {
components: {
myPage,
myPageTwo
}
}
</script>
子组件一 myPage.vue:
<template>
<div class="title-div" @click="changeEvent">111</div>
</template>
<script>
import bus from './bus'
export default {
name: 'MyPage',
data () {
return {}
},
methods: {
changeEvent() {
bus.$emit('text', 'ABCCD')
}
}
}
</script>
<style scoped>
.title-div {
width: 100%;
height: 100px;
background: yellow;
}
</style>
子组件二 myPage1.vue:
<template>
<div class="title-div">{{mag}}</div>
</template>
<script>
import bus from './bus'
export default {
name: 'MyPage',
data () {
return {
mag: '222'
}
},
mounted() {
bus.$on('text', val => {
this.mag = val
})
}
}
</script>
<style scoped>
.title-div {
width: 100%;
height: 100px;
background: red;
}
</style>
注意:需要通信的子组件要引入同一个bus.js,使用bus.$emit()发送消息,使用bus.$on()监听。
运行结果:(点击黄色区域更新红色区域文字)