zoukankan      html  css  js  c++  java
  • 非父子组件间的传值

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>非父子组件间的传值(Bus/总线/发布订阅模式/观察者模式)</title>
        <script src="./vue.js"></script>
    </head>
    <body>
    <div id="root">
        <child content="alex"></child>
        <child content="xu"></child>
    </div>
    <script>
        Vue.prototype.bus = new Vue(); //把绑定总线
    
        Vue.component('child', {
            data: function () {
                return {
                    selfContent: this.content
                }
            },
            props: {
                content: String,
            },
            template: '<div @click="handleClick">{{selfContent}}</div>',
            methods: {
                handleClick: function () {
                    this.bus.$emit('change', this.selfContent)  //向外触发事件
                }
            },
            mounted: function () {
                var this_ = this;
                this.bus.$on('change', function (msg) {
                    this_.selfContent = msg
                }) //监听事件,用到钩子函数mounted
            }
        });
        var vm = new Vue({
            el: '#root'
        })
    </script>
    </body>
    </html>
    
    <!--
    非父子组件间传值:
    1.Vuex
    2.总线机制/Bus/发布订阅模式/观察者模式:
       在Vue的prototype上定义bus属性 Vue.prototype.bus = new Vue();
       在组件的methods定义的方法里使用 this.bus.$emit('事件名', value); 触发事件并传值。
       在组件的mounted生命周期钩子里使用this.bus.$on('事件名', function(value){});来监听所定义的bus属性上对应的事件被触发,然后在回调函数里进行操作。
    
    -->
  • 相关阅读:
    07_Go语言 ( 切片)
    06_Go语言( 数组)
    05_Go语言( 流程控制)
    04_Go语言( 运算符)
    02_Go语言(变量和常量)
    01_Go语言(环境的搭建)
    云电脑直播简单指南
    统信UOS共享打印机配置
    #插头dp#洛谷 5074 Eat the Trees
    #状压dp#洛谷 3959 [NOIP2017 提高组] 宝藏
  • 原文地址:https://www.cnblogs.com/xuyxbiubiu/p/9988008.html
Copyright © 2011-2022 走看看