非父子组件之间的三种传值办法

非父子组件之间的传值
1.兄弟组件的传值:bus总线—发布订阅者—观察者模式
Vue.prototype.属性 = new Vue(),使Vue的原型上的属性等于Vue实例

<div id="root">
    <child content="miss"></child>
     <child content="mos"></child>
</div>
<script>
    Vue.prototype.bus = new Vue(); //兄弟间传值关键语句
    Vue.component('child', {
        data: function() {
            return {
                selfContent: this.content  //拷贝父组件参数,以便修改,子组件用到content的地方修改为selfContent
            }
        },
        props: {
            selfContent: String
        },
        template: '<div
            @click="handleClick">{{selfContent}}</div>
        >',
        methods: {
            handleClick: function() {
               // alert();
               this.bus.$emit('change', this.selfContent);
            }
        },
        mounted: function() {
        //保存this指针,后续this.bus使得this.selfContent的this指向会改变
            var this_ = this; 
            this.bus.$on('change', function(msg) {
                this_.selfContent = msg; //子组件不可以更改父组件值,若需要改要拷贝值作为自己的属性值
            })
        }

    })
    var vm = new Vue({
        el: '#root'
    })
</script>

2.利用vuex状态管理进行状态共享达到传值的目的
3.以及当兄弟节点有共同的父节点时可以利用两次父子传值达到兄弟传值的目的。

猜你喜欢

转载自blog.csdn.net/Qian_mos/article/details/88872326
今日推荐