【从头撸到脚】vue3 + TS

153 阅读1分钟

dush.webp

前言


“用是用的vue3,怎么写起来还有vue2的影子?”

相信大多数开发者都有这样的感受,好好的一个Composition API 给写成了 Options API的样子。这就好像披着一副而立的躯壳,血肉却已古稀。不仅别人看代码感到奇怪,自己写的也很奇怪,然后不由自主的感到了一个可怕的词语 -- LOW

说实话我也是其中一员,虽然vue3生态已经较为成熟了一段时间,但迫于业务压力一直没机会尝鲜,苦苦等了“五”年,终于等到了一个机会(”你知道我这五年是怎么过来的么“)
以下是我总结出来的尽量避免vue2影子的地方,主要为了时刻鞭策自己,所以记录下来。代码不难,但其实还是能体会到vue3完全支持TS的含义。

const count = ref<number | null>(null) // 重点
const changeCount = (num: number) => { 
    if(!count.value){...}
    count.value = num
}
changeCount()
// 这招对于初始化页面不想显示0 是很管用的
  • Props
使用
const props =  defineProps<{  // in vue3
    msg: string
}>
代替
const props = defineProps({  // in vue2
     msg: ''
})
// 诠释了 定义结构及类型 和 初始化变量 的区别
使用
<Count />
const props = withDefaults(defineProps<{ msg: '' }>, {
    msg: "halo"
}) 
代替
<Count :msg="halo"/>
const props = defineProps<{
    msg: ''
}>
// 函数组合感更重,有那味儿了
  • Emits
// father
<Count 
    @add-event="addEventFunction"
    @dec-event="decEventFunction"
    />
const addEventFunction= (num) => {
    count.value+= num
}
const decEventFunction= (num) => {
    count.value-= num
}
// children
const emit = defineEmits<{
    (event: "add-event", payload: number): void;
    (event: "dec-event", payload: number): void;
}>()

Keep Update And Working More Like A Tech.