Vue 非父子组件的数据传递

2020-10-11  本文已影响0人  云凡的云凡

Vue 复杂的组件之间传值有两种常用的方法,数据层框架vuex和(Bus/总线/发布订阅模式/观察者模式)。在这里先记录一下Bus如何使用。


image.png

点击hello,world会变成hello,点击world也一样

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>15Vue 非父子组件的数据传递</title>
    <script src="./vue.js"></script>
</head>

<body>
    <div id="app">
        <child content='hello'></child>
        <child content='world'></child>
    </div>
    <script>
        Vue.prototype.bus = new Vue()  //1.把bus挂载到Vue的原型上,这样全局都可以通过this.bus访问bus,并且把Vue的实例赋值给bus。
        Vue.component('child', {
            data: function () {
                return {
                    selfContent: this.content
                }
            },
            props: {
                content: String
            },

            template: '<div @click="handleClick">{{selfContent}}</div>',
            methods: {
                handleClick: function () {
                    // 2.bus 是vue的一个实例
                    this.bus.$emit('change', this.selfContent)  //先点击hello时,world会变成hello,然后再点击变成hello的world想把先前点击的hello一起变成world,但是会一直但是hello,如果先点击的是world,也是这种情况,如果不答应msg,还以为只能点击一次呢。
                    this.bus.$emit('change', this.content)//传递出去的应该是一开始从父组件传过来的content
                }
            },
            mounted: function () {
                var this_ = this
                this.bus.$on('change', function (msg) {
                    //3. alert(msg)  点击一次会弹出两次,因为child组件都绑定了handleClick
                    this_.selfContent = msg
                    // console.log(msg);  点击一次输出两次
                })
            },
        })
        var vm = new Vue({
            el: "#app",
        })
    </script>
</body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读