1. 程式人生 > >Vue 非父子關係的傳值 bus 訂閱者模式

Vue 非父子關係的傳值 bus 訂閱者模式

1:通過建立Bus 的特性來訂閱

Vue.prototype.bus=new Vue()

2: 必須要儲存當前的作用域

var this_=this
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

</head>
<body>

    <div id="root">

        <child content="韓曉"></child>
        <child content="vily"></child>

    </div>

    <script>

        Vue.prototype.bus=new Vue()

        Vue.component('child',{

            props:{
                content:String
            },
            data:function(){
                return {
                    text3:this.content
                }
            },

            template:'<div @click="clickItem">{{text3}}</div>',

            methods:  {

                clickItem:function () {

                    this.bus.$emit('change',this.text3)
                }
            },
            mounted:function () {
                var this_=this
                this.bus.$on('change',function (msg) {
                    this_.text3=msg
                })
            }
        })

        new Vue({

            el:'#root'
        })

    </script>
</body>
</html>