14-非父子组件之间的传值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>非父子组件之间的传值【Bus/总线/发布订阅模式/观察者模式】</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/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',{
            data:function(){
                return {
                    selfcontent : this.content
                }
            },
            props:{
                content:String
            },
            template:'<div @click="click">{{selfcontent}}</div>',
            methods: {
                click:function(){
                    // console.log(this.content);
                    this.bus.$emit('change',this.selfcontent)
                }
            },
            mounted() {
                var _this =this;
                this.bus.$on('change',function(res){
                    // alert(res);
                    _this.selfcontent=res;
                })
            },
        });
        var app = new Vue({
            el:'#app',
            template:'',
            data:{},
            methods: {
                
            },
        })
    </script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/suni1024/p/11540257.html