非 Prop 的特性

一个非 prop 特性(属性)是指传向一个组件,但是该组件并没有相应 prop 定义的特性。

Vue.component('test-prop', {
  // 在组件props中只定义了param1
  props: ['param1'],
  inheritAttrs: false,  // 详情见 ↓ 附录1
  template: '
', mounted() { console.log(this.param1); // 值1 console.log(this.param2); // undefined console.log(this.$attrs); // 返回父作用域中非 prop 的特性 (class 和 style 除外)的对象集合 console.log(this.$attrs.param1); // undefined console.log(this.$attrs.param2); // 值2 console.log(this.$listeners); // 返回父作用域中的 (不含 .native 修饰器的) v-on 事件集合 console.log(this.$listeners.event1); // fn1 console.log(this.$listeners.event2); // undefined this.$emit('event1'); } })

通过 $attrs$listeners 属性可以降低在不使用Vuex以及事件总线的情况下,组件跨级props以及事件传递的复杂度。












附录1:
inheritAttrs
默认情况下父作用域的非 prop 的特性会 挂载到 根元素(属性)上,通过设置 inheritAttrsfalse可去除。
注意:这个选项不影响 classstyle 绑定。

将 `inheritAttrs` 设为 `false` 后

摘录于:Vue官网

你可能感兴趣的:(非 Prop 的特性)