Vue -- 非父子组件传值(十八)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38287952/article/details/88262526

示意图 (各个组件传值)

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>非父子组件间的传值(Bus/总线/发布订阅模式/观察者模式)</title>
    <script src="../vue.js"></script>
</head>
<body>
    <div id="app">
        <child content="Dell"></child>
        <child content="Lee"></child>
    </div>

<script>
    Vue.prototype.bus = new Vue();

    Vue.component("child", {
        props: {
            content: String
        },
        data: function() {
            return {
                selfContent: this.content
            }
        },
        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;
            });
        }
    });
    var vm = new Vue({
        el: "#app"
    });
</script>
</body>
</html>

 

展开阅读全文

没有更多推荐了,返回首页