zoukankan      html  css  js  c++  java
  • vue二十二:vue基础之事件总线实现非父子通信

    事件总线工作原理

    在代码中实现

    创建非父子关系的组件

    创建中央事件总线(空的vue实例)

    mounted生命周期函数,在当前组件的dom创建完后就会调用

    在mounted生命周期中绑定订阅事件总线

    绑定发布事件总线

    获取发布的状态

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue.js"></script>
    </head>
    <body>
    <div id="app">
    <author></author>
    <user></user>
    </div>

    <script>
    var bus = new Vue() // 空Vue实例,就是中央事件总线

    Vue.component('author', {
    template: `
    <div style="background: blue">
    公众号作者
    <input type="text" ref="inputText">
    <button @click="handleClick()">发布文章</button>
    </div>`,
    methods:{
    handleClick(){
    bus.$emit('msg', this.$refs.inputText.value)
    }
    }
    })
    Vue.component('user', {
    template: `
    <div style="background: green">
    微信用户
    </div>`,
    mounted() { // 生命周期函数,在当前组件的dom创建完后就会调用
    bus.$on('msg', (data) => {
    console.log('收到推送了', data)
    })
    console.log('生命周期函数,在当前组件的dom创建完后就会调用')
    }
    })


    new Vue({
    el: "#app",
    })

    </script>
    </body>
    </html>
    讨论群:249728408
  • 相关阅读:
    nth-child与nth-of-type
    改变事件绑定的this的问题
    瀑布流的一些CSS实现方式
    事件捕获与冒泡的再探
    为学
    ECharts导出word 图表模糊失真
    垂直对齐:vertical-align:super属性
    Vuex- Action的 { commit } {commit}是什么写法
    修改对象中的属性名
    echarts 角度渐变环形图心得
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/12384381.html
Copyright © 2011-2022 走看看