Vue组件传值

136 阅读1分钟

Vue 组件传值

1.父组件传递子组件

1.使用props属性传递

// 父组件
<Parent>
  <Child msg="hello,my child"></Child>
</Parent>

// 子组件
export default {
  name: "Child",
  props: {
    msg: String,
  }
}

2.使用refs传值

// 父组件
<Parent>
  <Child refs="cld"></Child>
</Parent>

// 父组件通过引用修改子组件的值
this.$refs.cld.name = "小王";

3.使用$children

// 父组件
<Parent>
  <Child></Child>
</Parent>

// 父组件通过children来修改子组件的值
this.$children[0].name = "小张";

2.子组件传递父组件

通过自定义事件

// 父组件定义子组件触发响应事件
<Parent>
    <Child @say="childSay($event)"></Child>
</Parent>

// 子组件触发事件
this.$emit("say","hello parent");

3.兄弟组件通信

使用父组件作为桥梁

// 兄弟1,为父组件绑定监听事件
this.$parent.$on("say",handle(msg));

// 兄弟2,触发父组件事件
this.$parent.$emit("say","hello brother");

4.祖孙组件通信

通过provide/inject API实现,实际开发少,源码多

// 祖先组件
export default {
  name: "Ancestor",
  provide: {
    msg: "hello descendant",
  }
}

// 后代组件
export default {
  name: "Descendant",
  inject: ["msg"]
}

5.任意组件传值

1.事件总线:创建一个类负责事件派发、监听和回调管理

// 观察者模式
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));
    }
  }
}

或者直接使用一个新的Vue实例,Vue实例实现了emit和on

Vue.prototype.$bus = new Vue();

2.vuex