inheritattrs详解

发布时间:2023-05-22

一、什么是inheritAttrs?

inheritAttrs是一个在自定义组件中常用的属性,可以让组件内部包含的某一个子组件继承父组件的属性。 有些时候,我们可能想让某一个子组件取得父组件的某些属性,但又不想在每个子组件里面都去写一遍父组件的相同属性值,这个时候就可以用到inheritAttrs属性。 inheritAttrs可以让父组件的某个属性值传递给子组件,在子组件内部使用props接收使用。

二、如何使用inheritAttrs?

在Vue中,可以通过 $attrs 来获取父组件里面传递过来的属性值,这些属性并不会被props特性所捕获,所以需要注意判断一下传递过来的属性是否存在于子组件中。

Vue.component('child', {
  template: '<div><slot></slot></div>',
  inheritAttrs: false, // 关闭默认的继承attrs行为
  mounted () {
    console.log(this.$attrs) // { class: 'myClass' }
  }
})
Vue.component('parent', {
  template: '<child class="myClass"></child>'
})

可以看到,在子组件中打印 this.$attrs 就能获取到父组件传递过来的属性值,而在父组件template中直接使用属性 class="myClass" 即可。

三、如何自定义传递过来的属性名称?

除了使用默认的属性名称,还可以自定义传递过来的属性名称。

Vue.component('child', {
  props: ['myColor'],
  template: '<div :style="{ color: myColor }"><slot></slot></div>',
  inheritAttrs: false,
  mounted () {
    console.log(this.$attrs) // { color: 'red' }
  }
})
Vue.component('parent', {
  template: '<child v-bind:my-color="attrs.color" color="red"></child>'
})

可以看到,在父组件template中传递了一个color属性值,使用了 v-bind:my-color="attrs.color"attrs 中的 color 传递给了 my-color

四、继承指令

除了传递属性值,还可以继承某些指令,比如 v-bindv-on等等。 使用inheritAttrs: false关闭默认继承attrs,然后自定义属性继承v-bind指令。

Vue.directive('highlight', {
    bind(el, binding, vnode) {
        el.style.backgroundColor = binding.value;
    }
});
Vue.component('child', {
    template: '<div v-bind="$attrs"><slot></slot></div>',
    inheritAttrs: false
});
Vue.component('parent', {
    template: '<child v-bind:highlight="\'yellow\'" v-bind:class="\'myClass\'"></child>'
});

这个时候,子组件的 classhighlight 指令就能继承到父组件。

五、总结

inheritAttrs能让父组件的某个属性传递给子组件,在子组件内部使用props接收使用。在Vue中,可以通过 $attrs 来获取父组件里面传递过来的属性值,这些属性并不会被props特性所捕获。我们也可以自定义传递过来的属性名称,也可以继承某些指令。