非父子之间传值,可以采用发布订阅模式,这种模式在 Vue 中被称为总线机制,或者叫做Bus
/ 发布订阅模式 / 观察者模式
1、main.js
import Vue from 'vue'
import App from './App'
import router from './router'
async function start(){
Vue.prototype.bus = new Vue() //用于订阅
}
// 创建根实例
new Vue({
el: '#app', // 挂载的id
router, // 路由引入
components: { App }, // 组件
// 调用的模板语法 把app渲染挂载到页面
template: '<App/>'
})
start ()
Vue.prototype.bus = new Vue()
这句话的意思是,在 Vue 的prototype
挂载了一个bus
属性,这个属性指向 Vue 的实例,只要我们之后调用 Vue 或者new Vue
时,每个组件都会有一个bus
属性,因为以后不管是 Vue 的属性还是 Vue 的实例,都是通过 Vue 来创建的,而我在 Vue 的prototype
上挂载了一个bus
的属性。
2、父组件 。 (home组件向news组件传值)
<template>
<div id="app">
<v-home></v-home>
<hr>
<br>
<v-news></v-news>
</div>
</template>
<script>
import Home from './components/Home.vue'
import News from './components/News.vue'
export default {
name: "app",
components:{
'v-home':Home,
'v-news':News
},
data() {
return {
msg:'hello vue world!',
}
},
}
</script>
<style>
</style>
3、Home.vue组件
<template>
<div id="home">
{{msg}}
<br>
<button @click="emitNews()">send message to News Page </button>
</div>
</template>
<script>
export default {
data(){
return {
msg:'i am home component!'
}
},
methods:{
emitNews(){
this.bus.$emit('change', this.msg)
}
}
}
</script>
<style>
</style>
4、News.vue 组件
<template>
<div id="news">
{{msg}}
<br>
<button @click="emitHome()">send message to Home Page </button>
</div>
</template>
<script>
export default {
data(){
return {
msg:'i am news component!'
}
},
mounted(){
this.bus.$on('change', (data)=>{
console.log(data)
})
})
}
}
</script>
<style>
</style>
组件被挂载之前会执行mounted
钩子函数,所以可以在mounted
中对change
事件进行监听。