官网解释
一个非 prop 的 attribute 是指传向一个组件,但是该组件并没有相应 prop 定义的 attribute。
因为显式定义的 prop 适用于向一个子组件传入信息,然而组件库的作者并不总能预见组件会被用于怎样的场景。这也是为什么组件可以接受任意的 attribute,而这些 attribute 会被添加到这个组件的根元素上。
例如,想象一下你通过一个 Bootstrap 插件使用了一个第三方的 组件,这个插件需要在其 上用到一个 data-date-picker attribute。我们可以将这个 attribute 添加到你的组件实例上:
<bootstrap-date-input data-date-picker="activated"></bootstrap-date-input>
然后这个 data-date-picker="activated" attribute 就会自动添加到 的根元素上。
例子
父组件
//父组件
<template>
<div>
<childDom :hasThis="hasThis" :noThis="noThis"> </childDom>
</div>
</template>
<script>
import childDom from "./sonDom.vue";
export default {
data() {
return {
hasThis: "Hello,world",
noThis: "Hello,rui",
};
},
components: { childDom },
};
</script>
子组件
<template>
<div>
<p>hasThis:{{ hasThis }}</p>
</div>
</template>
<script>
export default {
name: "son-dom",
props: ["hasThis"],
};
</script>
因为子组件中没有prop为noThis这个属性,所以继承了父组件的特性,如果在子组件的props里接收noThis则DOM中就不会有这个属性。
如果在子组件接收noThis
<template>
<div>
<p>hasThis:{{ hasThis }}</p>
</div>
</template>
<script>
export default {
name: "son-dom",
props: ["hasThis","noThis"],
};
</script>
这时候dom结构上是不会存在noThis的属性。
禁用attribute
Vue.component('my-component', {
inheritAttrs: false,
// ...
})
使用inheritAttrs可以禁止子组件继承父组件的attribute,即即使子组件没有接收父组件的属性,父组件传入的属性也不会出现在子组件dom的父元素上。