vue组件通信

100 阅读1分钟
  1. 父传子

    • 属性props
      // 父
      <HelloWorld msg="Welcome to Your Vue.js App"/>
      // 子
       props: {msg: String}
      
    • $attrs(未在props中申明的属性)
      // 父
      <HelloWorld m1="hello world"/>
      // 子
      <h2>{{$attrs.m1}}</h2>
      
    • 引用refs
         // 父
         <HelloWorld ref="helloWorld"/>
         this.$refs.helloWorld.m2 = 'no'
         // 子
         data(){
             return {
                 m2:'yes'
             }
         }
      
    • $children 访问子元素
         this.$children[0].m2 = 'no'
      
  2. 子传递父

    • 自定义事件
          // 父
          <HelloWorld @clk="handle($event)"/>
          // 子
          this.$emit('clk','hello world')
      
  3. 兄弟组件

    • 通过共同的祖辈组件桥接 $parent$root
      this.$root.$emit('XX','yyy')
      this.$root.$on('XX',(val)=>{
          console.log(val)
      })
      
  4. 祖先与后代

    • provideinject

      //祖先
      export default{
         provide(){ // 同data申明
             return {
                 app:'you are right'
             }
         } 
      }
      // 后代
      export default{
          inject:['app'] // 同props申明
      }
      
  5. 任意两个组件之间

    • Vuex或者事件总线 Vue.prototype.$bus = new Vue()
    • 创建一个Bus类负责管理事件监听,派发和回调执行
      class Bus{
          constructor(){
              this.cbs = {}
          }
          $on(name,cb){
              this.cbs[name] = this.cbs[name] || []
              this.cbs[name].push(cb)
          }
          $emit(name,args){
            if(this.cbs[name]){
              this.cbs[name].forEach(cb=>cb(args))
            }
          }
      }