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

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>非父子组件传值(Bus/总线/发布订阅模式/观察者模式)</title>
    <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body>
<!--使用vuex 或者总线机制来解决非父子组件传值-->
<!--案例说明:点击Dell的时候Lee,当点击Lee的时候Dell 变成Lee

两个不相关的组件之间的传递
-->
    <div id="app">
        <child content="Dell"></child>
        <child content="Lee"></child>
    </div>
</body>
<script src="../node_modules/vue/dist/vue.min.js"></script>
<script>
    Vue.prototype.bus = new Vue()


    Vue.component('child',{
        data(){
            return {
                selfContent: this.content
            }
        },
        props:{
          content:String
        },
        template:'<div @click="handleClick">{{selfContent}}</div>',
        methods:{
            handleClick(){

                //1.我要把当前this.content传给另一个组件
                this.bus.$emit('change',this.selfContent)
            }
        },
        mounted(){
            var this_ = this
            //2.监听bus中的change时间
            //3.注意:我们不能修改父组件传过来的值例如content,我们在data中定义属性,把this.content如存入进去,我们来操作这个属性即可
            this.bus.$on('change',function (msg) {
                this_.selfContent = msg
            })
        }
    })
    let app = new Vue({
        el:"#app",

    })

</script>
</html>
本作品采用《CC 协议》,转载必须注明作者和本文链接
chenBJ
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!