vue组件的inheritAttrs属性
先看一个案例
子组件ChidComp.vue
<script>
export default {
inheritAttrs: true,
props: {
msg: String
},
mounted(){
console.log(this.$attrs.mesge);
}
}
</script>
<template>
<div >
<h2>{{ msg || 'No props passed yet' }}</h2>
</div>
</template>
父组件App.vue
<script>
import ChildComp from './ChildComp.vue'
export default {
components: {
ChildComp
},
data() {
return {
greeting: 'Hello from parent'
}
}
}
</script>
<template>
<ChildComp mesge="ssss" classd="ss"/>
</template>
页面效果:
说明:
我们在子组件ChildComp.vue中设定属性inheritAttrs=true(默认),在父组件中引用了子组件,并传入了两个非Prop的属性mesge、classd。检查元素可以看到两个属性被当作html属性渲染在子组件的根元素上。
当设置inheritAttrs=false时我们再看:
由此我们可以得出:inheritAttrs=false时,父组件传入子组件的非Prop【属性】不会被当作html属性渲染,不管是false还是true,非Prop属性都可以通过this.$attrs[key]来获取。
使用场景:inheritAttrs=false 搭配$attrs,适应在定义一些基础组件时,不希望自定义的【属性】被子组件里根元素继承,但又想指定在某个元素上继承使用(v-bind="$attr")