vue3-setup语法糖中的props+ts
vue3 新增了组合式api的语法糖,相应的props,也会有相应的变化。下面是我总结的三种。
<ButtonVue />
<hr />
<ButtonVue bgColor="red" content="按钮" />
<template>
<button :style="{ backgroundColor: bgColor }">{{ content }}</button>
</template>
<script setup lang="ts">
// 第一种: 使用这种方式可以设置props的 默认值 和 类型 和 是否可选
// const props = defineProps({
// content: {
// type: String,
// required: true
// },
// bgColor: {
// type: String,
// default: '#aac8e4'
// }
// })
// 第二种: ts 纯声明方式 这种方式不能设置默认值
// type Props = {
// content: string
// bgColor: string
// }
// const props = defineProps<Props>()
// 第三种: 那么可以使用 withDefaults
type Props = {
content: string
bgColor: string
}
const props = withDefaults(defineProps<Props>(), {
content: 'button',
bgColor: 'green'
})
// 注意 defineProps 与 withDefaults 都有一个返回值,
// 返回的是一个props对象,这个对象包含所有的props属性
console.log(props)
</script>
<style scoped>
button {
height: 40px;
width: 100px;
border: none;
border-radius: 5px;
}
</style>