Vue2.4 inheritAttrs $attrs $listeners 组件容器化

229 阅读1分钟

inheritAttrs 继承属性

子组件是否接收未被被声明的属性,除 classstyle

<!-- child.vue -->
<template>
    <label>
        Child
        <input type="check">
    </label>
</template>
<script>
export default {
    inheritAttrs: false
}
</script>
<!-- parent.vue -->
<child foo="foo" bar="bar"></child>

<!-- f12 --- inheritAttrs === true -->
<label foo="foo" bar="bar">
    Child
    <input type="check">
</label>

<!-- f12 --- inheritAttrs === false -->
<label>
    Child
    <input type="check">
</label>

$attrs

inheritAttrs === false,组件将传入的属性 v-bind:attr1 v-bind:attr2 v-bind:attr3 中声明为 props 的显示为HTML属性,将未声明的存在 $attrs 中,并可通过 v-bind="$attrs" 继续向孙子组件传递。

父组件 v-bind:foo="parent_foo" => 子组件 v-bind="$attrs" => 孙子 this.$attrs.foo

父组件 v-bind:foo="parent_foo" => 子组件 props: ['foo'] v-bind="$props" => 孙子 this.$props.foo

$listeners

父组件订阅子孙组件事件 v-on:event1 v-on:event2 (除 .native 外)

子组件将传入订阅保存在 $listeners 中,并可以通过 v-on="$listener" 继续向孙子组件传递。

父组件 v-on:foo="foo_handle" => 子组件 v-on="$listeners" => 孙子 v-on:event="$emit('foo')"