Vue——非父子组件间传值(Bus/总线/发布订阅模式/观察者模式)

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>非父子组件间传值(Bus/总线/发布订阅模式/观察者模式)</title>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>

    <body>
        <div id="root">
            <child content="dell"></child>
            <child content="lee"></child>
        </div>
        <script type="text/javascript">
            Vue.prototype.bus = new Vue()

            Vue.component('child', {
                props: {
                    content: String
                },
                data() {
                    return {
                        selfContent: this.content
                    }
                },
                template: '<div @click="handleClick">{{selfContent}}</div>',
                methods: {
                    handleClick() {
                        this.bus.$emit('change', this.selfContent)
                    }
                },
                mounted() {
                    var _this = this
                    this.bus.$on('change', (msg) => {
                        _this.selfContent = msg
                    })
                }
            })
            var vm = new Vue({
                el: '#root'
            })
        </script>
    </body>

</html>

 

posted @ 2019-10-28 17:46  嘆世殘者——華帥  阅读(153)  评论(0编辑  收藏  举报