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属性上对应的事件被触发,然后在回调函数里进行操作。
    
    -->
  • 相关阅读:
    更好的处理 Python 多工程 import 依赖
    Django 前后台的数据传递
    Django传递数据给JS
    nodejs 设置跨域访问
    Node.js + Express
    前端用户输入校验--基于JQ
    git统计当前分支提交次数
    gitlab相关
    CentOS7使用firewalld打开关闭防火墙与端口
    puppeteer安装/爬取数据
  • 原文地址:https://www.cnblogs.com/xuyxbiubiu/p/9988008.html
Copyright © 2011-2022 走看看