非父子组件间的传值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>非父子组件间的传值(Bus/总线/发布订阅模式/观察者模式)</title>
    <script src="./vue.js"></script>
</head>
<body>
<div id="root">
    <child content="alex"></child>
    <child content="xu"></child>
</div>
<script>
    Vue.prototype.bus = new Vue(); //把绑定总线

    Vue.component('child', {
        data: function () {
            return {
                selfContent: this.content
            }
        },
        props: {
            content: String,
        },
        template: '<div @click="handleClick">{{selfContent}}</div>',
        methods: {
            handleClick: function () {
                this.bus.$emit('change', this.selfContent)  //向外触发事件
            }
        },
        mounted: function () {
            var this_ = this;
            this.bus.$on('change', function (msg) {
                this_.selfContent = msg
            }) //监听事件,用到钩子函数mounted
        }
    });
    var vm = new Vue({
        el: '#root'
    })
</script>
</body>
</html>

<!--
非父子组件间传值:
1.Vuex
2.总线机制/Bus/发布订阅模式/观察者模式:
   在Vue的prototype上定义bus属性 Vue.prototype.bus = new Vue();
   在组件的methods定义的方法里使用 this.bus.$emit('事件名', value); 触发事件并传值。
   在组件的mounted生命周期钩子里使用this.bus.$on('事件名', function(value){});来监听所定义的bus属性上对应的事件被触发,然后在回调函数里进行操作。

-->

 

posted @ 2018-11-20 11:44  alexbiu  阅读(185)  评论(0编辑  收藏  举报