vue 非父子组件传值

非父子之间传值,可以采用发布订阅模式,这种模式在 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事件进行监听。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值