vue3的setup语法糖

2023-06-09,,

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) //获取到子组件暴露出的属性

vue3的setup语法糖的相关教程结束。

《vue3的setup语法糖.doc》

下载本文的Word格式文档,以方便收藏与打印。