Vue(四)props 和 $attrs 属性

176 阅读1分钟

props 属性

父组件调用子组件,通过v-bind:属性传参,子组件通过 props 接收数据

//父组件
<template>
  <son v-bind:name="username" />
</template>
<script>
import son from './son.vue'; 
export default { 
  components: { son }, 
  data() { 
    return { 
      username: 'lucy' 
    } 
  } 
}
</script>

son.vue

//子组件
<template>
  <div> {{ name }} </div>
</template>
export default {
  props: {
    ['name']
  }
}

props 的不同写法

  • 数组
props: ['name','id']
  • 对象
props: {
  name: String,
  id: Number
}
  • 更复杂的写法
props: {
  name: {
    type: String,
    required: true,  // 是否必须
    default: ''  // 如果父组件没传,用默认值
  },
  id: {
    type: Number,
    required: false,
    default: 0
  }
}

$attrs:非 props 属性

为子组件添加属性,但是不希望通过子组件的 props 去接收,则用$attrs去获取。

为子组件设置了两个属性 class、data-user

//父组件
<template>
  <son class="username" :data-user="username" />
</template>
<script>
  ...
  data() { 
    return { 
      username: 'lucy' 
    } 
  } 
</script>

在子组件里获取

<div>
  {{ $attrs['data-user'] }}
</div>

还可以在 methods 里使用this.$attrs['class']this.$attrs['data-user']

注意

当组件返回单个根节点时(template下只有一个div根元素),这些非 props属性直接添加到该 div 根节点上作为其属性。

如果希望使指定的某个元素上添加这些属性,使用v-bind="$attrs",这样根元素和该元素都会有这些属性。