vue组件传值详解

全局组件VS局部组件

  1. 全局组件

全局可调用,可在一个或多个挂在了Vue实例的DOM节点内使用该组件。


    
  1. 局部组件

在Vue实例内声明的组件,只能在该实例内调用,局部组件和全局组件同时存在(组件名相同)时,局部组件会覆盖全局组件。


    

组件间通信方案

  1. 通过props传递

  2. $emit触发自定义事件

  3. 使用 ref

  4. 总线,EventBus

  5. parent/root

  6. attrslisteners

  7. ProvideInject

  8. Vuex

父->子

父组件通过属性赋值的方式向子组件传值,子组件通过props接收,使用。


    

子->父

子组件通过向外触发方法的方式向父组件传值。


    
{{total}}

ref

父组件获取子组件实例,调用子组件方法、获取子组件数据

// 子组件


this.$refs.son  // 子组件实例,可继续 . 拿到对应数据

EventBus

适用于:兄弟组件、无关系组件

// 创建总线(vue 已经实现了Bus)
class Bus {
    constructor(){
        this.callbacks = {};    // 存放事件的名字
    }
    $on(name,fn){
        this.callbacks[name] = this.callbacks[name] || [];
        this.callbacks[name].push(fn);
    }
    $emit(name,args){
        if(this.callbacks[name]){
            this.callbacks[name].forEach(cb => cb(args));
        }
    }
}

// main.js (挂在在vue实例的原形上)
Vue.prototype.$bus = new Bus();

// 未完……

你可能感兴趣的:(vue组件传值详解)