vue.js单文件组件中非父子组件的传值

最近在研究vue.js,总体来说还算可以,但是在web开发群里有一些人问在单文件组件开发模式中非父子组件如何传值的问题,今天在这里讲讲,希望对大家有所帮助! 
在官网api中的这段讲解很少,也很模糊;官网中说明如下:

非父子组件通信:
有时候两个组件也需要通信 (非父子关系)。在简单的场景下,可以使用一个空的 Vue 实例作为中央事件总线:
var bus = new Vue();
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
  // ...
})

那么这一段在单文件组件开发模式中具体怎么用呢? 
首先在main.js中加入data,如下:

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
  data:{
    bus:new Vue()
  }
})

如何获取到这个空的vue对象 bus呢.在组件里面直接调用这个this.$root

<template>
    <div class="title" @click="change(msg)">{{ msg }}</div>
</template>
<script>
    export default {
        name: 'first',
        data() {
            return {
                msg: '我是首页'
            }
        },
        methods: {
            change(text) {
                this.$root.bus.$emit("hehe", text)
            }
        }
    }

</script>

然后在另一个组件内调用on,,使on事件接收,当然在组件销毁时解除绑定,使用off方法

<template>
    <h1>{{ msg }}</h1>
</template>
<script>
    export default {
        name: 'second',
        data() {
            return {
                msg: '我是第二页'
            }
        },
        created() {
            let that = this;
            this.$root.bus.$on("hehe", function (t) {
                that.msg = that.msg + t
            })
        }
    }

</script>

然后点击的时候就能传递值了,还等什么,快来试试吧!欢迎加入前端交流群496522155,备注:前端 
希望对你有帮助,~溜了~

原文:https://blog.csdn.net/weixin_37794497/article/details/77337613  

  

  

  

原文地址:https://www.cnblogs.com/robinunix/p/10876789.html