• 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
  • 相关阅读:
    第二个冲刺 6.3.4.学术诚信与职业道德
    第二个冲刺 Sprint
    css之清除浮动
    style和getComputedStyle(ff)和currentStyle
    php 中间件
    Vue 和 angular
    img 分区响应图
    PHP composer
    php实现文件上传,下载的常见文件配置
    php 命名空间
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/12384381.html
Copyright © 2020-2023  润新知