props 和 attrs 都可以获取外部属性,那他们有什么区别呢?
区别如下
- props 要先声明才能取值,attrs 不用先声明
- props 不包含事件,attrs 包含事件
- props 没有声明的属性,会跑到 attrs 里
- props 支持 string 以外的类型,attrs 只有 string 类型 示例:
// 父组件 ButtonDemo.vue
<template>
<h2>示例1</h2>
<div>
<Button disabled> 你好 </Button>
// 等价于 <Button :disabled="true"> 你好 </Button>
</div>
</template>
使用 attrs:disabled 为空字符串
// Button.vue
<template>
<button v-bind="$attrs">
<slot/>
</button>
</template>
使用 props:disabled 为true
// Button.vue
<template>
<button :disabled = "disabled">
<slot/>
</button>
</template>
<script lang="ts">
export default {
props:{
disabled:Boolean
}
}