vue3的defineProps接收类型注解

复制代码
 //这是没有用ts语法接收的props参数
defineProps({
     color: String,
     size: {
         type: String,
        required: false,
         default: 'middle'
     },
 })


//TS语法
//格式:withDefaults(defineProps<类型>(), { 默认值名:默认值})
第一种写法:
withDefaults(defineProps<{ color: string, size?: string }>(),{

     size: 'middle'

})

第二种写法:通过解构设置默认值 
const { color, size = 'middle' } = defineProps<{ color: string, size?: string }>()
//但这样会丢失数据 的响应式
// 解决办法: 下载 npm i -D @vue-macros/reactivity-transform
// 在vite.config.js里配置
// import ReactivityTransform from '@vue-macros/reactivity-transform/vite'

// export default defineConfig({
//   plugins: [ReactivityTransform()],
// })

第三种无默认值写法:这种是没有默认值不需要下载,不会丢失响应式
 const props = defineProps<{ color: string, size?: string }>()
 const { color, size = 'middle' } = props
 console.log(color, size);
复制代码

 

posted @   light丶  阅读(388)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示