vue3的setup语法糖

https://blog.csdn.net/weixin_44922480/article/details/127337914

 

https://blog.csdn.net/m0_63108819/article/details/125534809

 

defineProps

使用PropType类型验证

⽤⼀句简单的话来说,就是为了类型推论,让我们在使⽤属性的时候获取更丰富的类型提⽰,⽐如在这⾥我们定义了⼀个属性 list,使⽤ vue默认的 Array,只能确定它是⼀个数组类型,不能确定数组⾥⾯的每⼀项到底是什么样⼦的。你在 setup 中,看 props.list 就是⼀个any数组,但是如果使⽤PropType <ColumnProps[]> 这个时候,props.list 就变成⼀个 ColumnProps 的数组,你使⽤它的时候不论在 ts 中还是模版中都能获得类型的推断和⾃动补全等等。

Array 可以写成 Array as PropType<oneType[]>

Object 可以写成 Object as PropType

然后你可以定义你的type oneType = {}

//子组件
import { PropType, defineProps } from 'vue'
interface ColumnProps{
id: string;
title: string;
avatar: string;
description: string;
}
const props = defineProps<{
modelValue: String,
num?: Number,
list: Array<ColumnProps>
}>()
//或者
const prors = defineProps({
modelValue: {
type: String
},
num: {
type: Number,
default: 0
},
list:{
type:Array as PropType<ColumnProps[]>,
required:true
}
})

defineEmits

//子组件
const emit = defineEmits(['handleSubmit']);
//或者
const emit = defineEmits<{
(e: 'handleSubmit', num: number): void
}>()
const btn = ():void => {
emit('handleSubmit', 666666)
}

defineExpose

子组件暴露数据或者是方法

//子组件 children
const isShow = ref<boolean>(false)
const login = (): void => {
axios.post('/login').then()
}
defineExpose({ // 宏来显示指定组件中属性暴露出去
isShow,
login
});
//父组件
const
<children ref="childrenRef"></children>
const childrenRef: any = ref(null);
console.log(childrenRef.value.isShow) //获取到子组件暴露出的属性
posted @   顺·  阅读(82)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示