vue问题的随笔

91 阅读1分钟

1.$attrs属性

定义:父作用域中不作为 prop 被识别 (且获取) 的 attribute(属性) 绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。

//父组件
<template>
  <div>
    <child-select :option = 'options' allowClear="true" disabled="true"></child-select>   
  </div>
</template>
<script>
import childSelect from './child_select'
export default {
  components:{
    childSelect
  },
  data () {
    return {  
      options: [
        {
          name: '老王'
        },
         {
          name: '老李'
        },
         {
          name: '老朱'
        },
      ],
    }
  },
 </script> 
  
 //子组件
 <template>
  <div>
    <a-select style="width: 200px" @change="handleChange" :allowClear="$attrs.allowClear">
      <a-select-option v-for="(item,index) in option" :key="index">
        {{ item.name }}
      </a-select-option>
    </a-select>
  </div>
</template>
<script>
export default {
  props:{
    option:{
      default: [],
      type: String
    }
  },
}
</script>
  
 
结论: 子组件可以通过$attrs 获取父组件不为prop传递的属性,在封装组件中带来极大的便利