vue数据传递 <非父子>

作者: zz77zz | 来源:发表于2019-05-28 23:22 被阅读4次

2019年5月28日23:25

4-1 组件注意的细节

  • 组件里的data 必须是个函数 return {}

  • ref 的两种情况

    • 非组件 : this.$refs.xxx 获取的是dom
    • 组件里 : this.$refs.xxx 获取的是子组件的引用

4-2 父子组件传递

图片来源慕课网 侵权删
  • 父子组件

  • 非父子组件 vuex解决 学习成本高

    • 爷孙组件
    • 兄弟组件
    <!DOCTYPE html>
    <html>
    <head>
      <title>test for vue</title>
      <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js">  </script>
    </head>
    <body>
    <div id="app">
      <h3>非父子组件间传值(Bus/总线/发布订阅模式/观察者模式)</h3>
      <child content="Dad gives u"></child>
      <child content="This money"></child>
    </div>
    <script type="text/javascript">
    
    // 非父子组件 用总线机制 其实就是给vue挂了个全局的属性
      Vue.prototype.bus = new Vue()
    
      Vue.component('child',{
          props:{
              content:String
          },
          template:'<div @click="handleClick">{{content}}</div>',
          methods:{
              handleClick(){
                  // alert(this.content)
                  this.bus.$emit('explode_func',this.content)
              }
          },
          mounted:function(){
              var _that = this
              this.bus.$on('explode_func',function(msg){
                  alert(msg) //这里会跳出两次 以为组件有两个 都监听了方法
                  _that.content = msg
              })
          }
      })
    
      var app = new Vue({
          el:"#app"
      })
    
    </script>
    </body>
    </html>  
    
    报错
    其实就是单向数据流 - 子组件不能修改父组件传递过来的值 所以data里做个copy就好了
Vue.prototype.bus = new Vue()

    Vue.component('child',{
        props:{
            content:String
        },
        data(){
            return {
                selfContent:this.content
            }
        },
        template:'<div @click="handleClick">{{selfContent}}</div>',
        methods:{
            handleClick(){
                // alert(this.content)
                this.bus.$emit('explode_func',this.selfContent)
            }
        },
        mounted:function(){
            var _that = this
            this.bus.$on('explode_func',function(msg){
                alert(msg) //这里会跳出两次 以为组件有两个 都监听了方法
                _that.selfContent = msg
            })
        }
    })

    var app = new Vue({
        el:"#app"
    })

发布订阅/观察者模式 这两个模式 其实小程序写多了自然就特别容易理解

  • 其实还是得理解 暴露函数 跟监听函数 也就是子传父的理解 多写写练练 就熟悉了

相关文章

网友评论

    本文标题:vue数据传递 <非父子>

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