Vue中组件通信

Vue4年前 (2020)发布 小马大哥哥
601 0 0

props

⽗给⼦传值

// child
props: { msg: String }
// parent
<HelloWorld msg="Welcome to Your Vue.js App"/>

⾃定义事件

⼦给⽗传值

// child
this.$emit('add', good)
// parent
<Cart @add="cartAdd($event)"></Cart>

事件总线

任意两个组件之间传值常⽤事件总线 或 vuex的⽅式。

// 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.prototype.$bus = new Bus();
// child1
this.$bus.$on("foo", handle);
// child2
this.$bus.$emit("foo");

实践中通常⽤Vue代替Bus,因为Vue已经实现了相应接⼝

vuex

创建唯⼀的全局数据管理者store,通过它管理数据并通知组件状态变更。

组件通信最佳实践

$parent/$root

兄弟组件之间通信可通过共同祖辈搭桥,$parent或$root。

// brother1
this.$parent.$on('foo', handle)
// brother2
this.$parent.$emit('foo')

$children

⽗组件可以通过$children访问⼦组件实现⽗⼦通信。

// parent
this.$children[0].xx = 'xxx'

注意:$children不能保证⼦元素顺序

$attrs/$listeners

包含了⽗作⽤域中不作为 prop 被识别 (且获取) 的特性绑定 ( class 和 style 除外)。当⼀个组件没有
声明任何 prop 时,这⾥会包含所有⽗作⽤域的绑定 ( class 和 style 除外),并且可以通过 v-
bind=”$attrs” 传⼊内部组件——在创建⾼级别的组件时⾮常有⽤。

// child:并未在props中声明foo
<p>{{$attrs.foo}}</p>
// parent
<HelloWorld foo="foo"/>

refs

获取⼦节点引⽤

// parent
<HelloWorld ref="hw"/>
mounted() {
  this.$refs.hw.xx = 'xxx'
}

provide/inject

能够实现祖先和后代之间传值

// ancestor
provide() {
    return {foo: 'foo'}
}
// descendant
inject: ['foo']

插槽

插槽语法是Vue 实现的内容分发 API,⽤于复合组件开发。该技术在通⽤组件库开发中有⼤量应⽤。

匿名插槽

// comp1
<div>
    <slot></slot>
</div>
// parent
<comp>hello</comp>

具名插槽

将内容分发到⼦组件指定位置

// comp2
<div>
    <slot></slot>
    <slot name="content"></slot>
</div>
// parent
<Comp2>
    <!-- 默认插槽⽤default做参数 -->
    <template v-slot:default>具名插槽</template>
    <!-- 具名插槽⽤插槽名做参数 -->
    <template v-slot:content>内容...</template>
</Comp2>

作⽤域插槽

分发内容要⽤到⼦组件中的数据

// comp3
<div>
    <slot :foo="foo"></slot>
</div>
// parent
<Comp3>
    <!-- 把v-slot的值指定为作⽤域上下⽂对象 -->
    <template v-slot:default="slotProps">
    来⾃⼦组件数据:{{slotProps.foo}}
    </template>
</Comp3>
© 版权声明

相关文章

暂无评论

您必须登录才能参与评论!
立即登录
暂无评论...