inheritAttrs :默认值是true,如果是true的话,默认情况下父作用域的不被认作 props 的 attribute 绑定 (attribute bindings) 将会“回退”且作为普通的 HTML attribute 应用在子组件的根元素上,
即父组件传的属性会绑到子组件根元素上,如果设置成false,则回禁止这种行为。
$attrs :包含了父作用域中不作为 prop 被识别 (且获取) 的 attribute 绑定 (class
和 style
除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class
和 style
除外),并且可以通过 v-bind="$attrs"
传入内部组件——在创建高级别的组件时非常有用。
例:
<template>
<div class="hello">
<myInput v-model="msg" type="text" placeholder="请输入用户名"></myInput>
<myInput v-model="msg" type="password" placeholder="请输入密码"></myInput>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
msg: "Welcome",
};
},
components: {
"myInput": {
template: `<div><input :value="value" v-bind="$attrs"/><span>{{$attrs}}</span></div>`,
inheritAttrs:false,
props:['value'],
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
说明:
1.由于inheritAttrs设置为false,子组件的根元素没有绑定到根元素上,
设置成true时:
2.$attrs在显示的时候,没有显示value,是因为$attrs不包括props里的属性