inheritAttrs
当我们在使用组件时,为其传递的参数要在组件的props中进行定义,才能够使用。如果没有定义,则这个属性会作为这个DOM结构的attribute被渲染。
比如我们定义一个自定义组件father,给它传入一个undefinedValue属性,而在props中没有接收它:
<father undefinedValue="'this is an undefinedValue'" ></father>
此时它会作为这个节点的attribute显示

如果当这个没有定义的属性比较特殊的时候,可能会对我们的组件产生意外的影响,比如定义了一个未接收的type属性,那么input框的类别可能就改变了。
要防止将这个外部传来的值作为attribute,可以在组件中加上inheritAttrs:false
。
$attrs
在Vue中,如果有多层组件嵌套,那么要把值从最外层父组件传给底层的组件则需要一层层在props中接收所有的值,并传给下一层级的组件,非常麻烦。
解决这个问题的方法是,在每一层级的组件中,只在props中定义自己需要的数据,并将$attrs
传递给下一层级的组件(这样就不用接收所有的父级的属性,然后再将一部分传递给孙级组件)。其中$attrs
是一个对象,其中属性是所有目前还没有被props接收的attributes,所以给下一层级传递$attrs
时可以用传递对象时的快捷写法。
<body>
<div id="app">
<father v1="'value1'" v2="'value2'" v3="'value3'"></father>
</div>
</body>
father.vue
<template>
<div>
<p>v1 is {{v1}}</p>
<son v-bind='$attrs'></son>
</div>
</template>
<script>
import son from './son.vue'
export default {
inheritAttrs: false,
props: ['v1'],
components: {
son
}
}
</script>
son.vue
<template>
<div>
<p>v2 is {{v2}}</p>
<grandSon v-bind='$attrs'></grandSon>
</div>
</template>
<script>
import grandSon from './grandSon.vue'
export default {
props: ['v2'],
components: {
grandSon
}
}
</script>
grandSon.vue
<template>
<div>
<p>v3 is {{v3}}</p>
</div>
</template>
<script>
export default {
props: ['v3']
}
</script>
在调用最外层组件father时,传入了三个值,v1、v2、v3,father组件中只用了v1,同时将其余值通过$attrs传递给下一层的son,son组件只用了v2,同理将值传给grandSon。
通过这种方法,可以将外部传入的值用到需要的地方,相比于每一层用props接收所有值,要简便了不少。
网友评论