美文网首页
vuejs非父子组件传值

vuejs非父子组件传值

作者: 前端丶米店 | 来源:发表于2019-11-11 14:46 被阅读0次

    简单场景下,可以使用一个空的vue实例作为中央事件总线 进行通信

    <div id="root">
        <child content="childOne"></child>
        <child content="childTwo"></child>
      </div>
    
      <script>
        // bus 总线 进行非父子组件的传值
    
        Vue.prototype.bus = new Vue()
    
        Vue.component('child', {
            props: ['content'],
            data: function() {
                return {
                    myContent: this.content
                }
            },
            template: '<div @click="handleClick">{{myContent}}</div>',
            methods: {
                handleClick: function() {
                    this.bus.$emit('change', this.myContent)
                }
            },
            mounted: function() {
                var this_ = this;
                this.bus.$on('change', function(content) {
                    this_.myContent = content
                })
            }
        })
    
        var vm = new Vue({
          el: "#root"
        })
      </script>
    

    相关文章

      网友评论

          本文标题:vuejs非父子组件传值

          本文链接:https://www.haomeiwen.com/subject/uvzubctx.html