zoukankan      html  css  js  c++  java
  • 非父子组件间通信

    非父子组件之间的通信,可以通过一个空的 Vue 实例作为中央事件总线(事件中心),用他来触发事件和监听事件。

    在这里,如果是工作中的新手看了官网的例子直接上手写,会有些发懵。这个作为事件总线空的 Vue 实例我该写哪里去?因为工作中我们的组件都是互相独立的,不可能写一起的,作用域是不同的,所以需要稍作调整

    一、在 main.js 中初始化根 Vue 之前,添加一个 data 对象,内写入一个名为 Event 的空 Vue 对象,也就是中央事件总线
    new Vue({
      el: '#app',
      data:{
        Event: new Vue()
      },
      render: h => h(App)
    })
    
    二、在各组件中使用 Vue 的实例属性 $root 来访问我们当前组件树的根 Vue 实例,这样就可以使用

    vm.$root.Event 来访问我们定义的事件发射器 Event
    比如我在 Hello.vue 组件中想发送数据到 Vue.vue 组件中

    <template>
        <div class="hello">
            <h3>我是 {{name}} 组件</h3>
            <button @click="send">发送数据到Vue组件中</button>
        </div>
    </template>
    
    <script>
    export default {
        data(){
            return {
                name: 'Hello'
            }
        },
        methods:{
            send(){
                // 触发组件 Hello 中的事件
                               // $emit(事件名,数据)
                this.$root.Event.$emit('hello',this.name)
            }
        }
    }
    </script>
    

    Vue.vue 组件中进行接收

    <template>
        <div class="Vue">
            <h3>我是 {{name}} 组件</h3>
        </div>
    </template>
    
    <script>
    export default {
        data(){
            return {
                name: ''
            }
        },
        mounted(){
            // 在组件 Vue 创建的钩子中监听事件
                            // $on(事件名,数据)
            this.$root.Event.$on('hello',name => {
                this.name = name
            })
        }
    }
    </script>
    

    这样就可以实现数据的通信了


     
    非父子组件通信
  • 相关阅读:
    JS 语法: document.getElementById没有括号
    c#,WinForm中读写配置文件App.config
    System.Data.SQLite数据库简介
    把JS 脚本嵌入CS运行
    Syteline Receiving By Purchase Orders Report
    TSQL DATEPART() Functions
    TSQL CONVERT Functions
    TSQL CAST Functions
    接口(Interface)替代抽象(Abstract)
    独立子查询
  • 原文地址:https://www.cnblogs.com/wu971023-/p/8985166.html
Copyright © 2011-2022 走看看