inheritAttrs和$attrs让组件更灵活

inheritAttrs和$attrs的作用:

  当需要将父组件的props传递到子组件中,而子组件的需要接收到props的节点有父级容器,那么就需要用到这两个属性。

  将inheritAttrs设置为false,在子组件需要接收props的节点上加上 v-bind='$attrs'

 

  如果父组件中在子组件的标签上添加了props属性(如:placeholder),希望将这些props属性直接放到子组件的表单组件(如:input)上,并且input外层有一层容器(input-container),就需要用到inheritAttrs和$attrs搭配。

 

封装一个input组件:

1、components/MyInput.vue:

<template>
  <input />
</template>

2、使用:

<template>
  <div id="app">
    <MyInput v-model="message" type='text' placeholder="请输入用户名"></MyInput>
    <MyInput v-model="message" type='password' placeholder="请输入密码"></MyInput>
  </div>
</template>
<script>
import MyInput from '@/components/MyInput'
export default {
  data() {
    return { message: 123 }
  },
  components: { MyInput }
}
</script>

3、效果:

但往往有的时候封装的input外层有层盒子,如下:

<template>
  <div class="input-container">
    <input />
    {{$attrs}}
  </div>
</template>

此时,可以看到父组件传来的属性都绑定到父容器身上了,所以没有效果

将inheritAttrs设置为false

<script>
export default {
  inheritAttrs: false
}
</script>

会发现父容器和input都没有了父组件传来的属性

再在需要接收父组件属性的标签上通过 v-bind='$attrs' 接收父组件的属性

<template>
  <div class="input-container">
    <input v-bind="$attrs" />
    {{$attrs}}
  </div>
</template>
<script>
export default {
  inheritAttrs: false
}
</script>

就可以正常显示了

要注意,当使用props接收了属性,那么这个属性就不在$attrs中了

<template>
  <div class="input-container">
    <input v-bind="$attrs" />
    {{$attrs}}
  </div>
</template>
<script>
export default {
  props: ['value'],
  inheritAttrs: false
}
</script>

可以通过 :value='value' 绑定【也可以通过属性合并v-bind="{ value, ...$attrs }"】

<template>
  <div class="input-container">
    <input v-bind="$attrs" :value="value" />
    {{$attrs}}
  </div>
</template>
<script>
export default {
  props: ['value'],
  inheritAttrs: false
}
</script>

 

posted @ 2021-08-10 18:00  吴小明-  阅读(124)  评论(0编辑  收藏  举报