美文网首页
Vue的组件通讯多种实现方式

Vue的组件通讯多种实现方式

作者: key君 | 来源:发表于2019-09-29 10:06 被阅读0次

组件化:

组件化是vue的核心思想,它能提高开发效率,方便重复使用,简化调试步骤,提升整个项目的可维护性,便于多人协同开发。

组件通讯:

父组件=>子组件

属性props

//child

  props:{    
      msg:String,    
      default: ''  
}

//parent

<HelloWorld msg="hello world"/>

特性$attrs

//child:并没有在props中声明属性foo

<h1>{{$attrs.foo}}</h1>

//parent

<HelloWorld foo="hello world"/>

引用refs

//child 在data里面定义属性foo

 <h1>{{foo}}</h1>

//parent

<HelloWorld ref="hw"/>

mounted(){      

    this.$refs.hw.foo = 'hello world1'   

 }

children

//child 在data里面定义属性foo 

<h1>{{foo}}</h1>

//parent 注意是取子元素

<template>  

    <div id="app">    

           <HelloWorld ref="hw"/>  

    </div>

</template>

mounted(){      

    this.$children[0].foo = 'hello world2'    

}

子组件=>父组件:自定义事件

PS:谁派发,谁监听

子组件派发事件,实际上最后也是子组件在监听这个事件


//children

this.$emit('add',this.add);

//parent

<HelloWorld @add="cartAdd"/>

methods:{      

    cartAdd(params){        

        console.log(params);     

     }   

 }

兄弟组件之间的通讯

通过共同的祖辈组件搭桥,parent或root

组件1让父组件发信号,组件2让父组件监听,然后执行组件2要执行的方法


//组件2

this.$parent.$on('foo',handle)

//组件1

this.$parent.$emit('foo')

组件和后代之间

如果是嵌套层数太多,不太适宜用props传值,此时可以用provide/injuct实现祖先给后代传值


//parent

provide(){     

    return{        

        something: 'hellowween'      

    }   

 }

//子组件或孙子组件

{{something}}
//写法可以跟props一样写成对象

inject:['something']

Bus总线

//抽出一个bus.js的公共类


export default class Bus{

    constructor(){

        this.callbacks = {};

    }

    $on(name,fn){

        this.callbacks[name] = this.callbacks[name] || [];

        this.callbacks[name].push(fn);

    }

    $emit(name,args){

        if(name,args){

            if(this.callbacks[name]){

                this.callbacks[name].forEach(cb => cb(args));

            }

        }

    }

}

//在main.js实例化引用

import Bus from './utils/bus'
Vue.prototype.$bus = new Bus();

//children1

this.$bus.$emit('foo','helloworld1');

//children2

this.$bus.$on('foo',(arg)=>{
        console.log(arg);
    });

相关文章

网友评论

      本文标题:Vue的组件通讯多种实现方式

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