TypeScript在vue中的使用解讀
主要介紹 TypeScript 在 vue 中的使用,還有一些j注釋起來的 js 代碼做對照
參考鏈接:合成 API 的TypeScript
vue3中配合使用TS,還需要額外安裝一個vscode插件:Typescript Vue Plugin

1. 父傳子 defineProps
父組件中
<script setup lang="ts">
import { ref } from 'vue';
import MyComVue from './components/MyCom.vue';
let money = ref(100)
</script>
<template>
<div style="padding: 20px; margin: 20px; border: 1px solid red">
<h1>父組件</h1>
<p>傳給子組件:{{money}}</p>
<MyComVue
:money="money"
car="特斯拉"
/>
<MyComVue
:money="money"
/>
</div>
</template>
子組件中
<script setup lang="ts">
// 1. js中
// const props = defineProps({
// money:{
// type: Number,
// require: true
// },
// car: {
// type: String,
// required: true
// }
// })
// 2. ts中
// props可以通過解構(gòu)來指定默認(rèn)值,將指定默認(rèn)值的變量定義為可選參數(shù)
const {money, car='GTR'} = defineProps<{
money: number
car?:string
}>()
</script>
<template>
<div style="padding: 20px; margin: 20px; border: 1px solid red">
<h1>子組件</h1>
<p>從父組件接收 {{money}} {{car}}</p>
</div>
</template>
注:提供的默認(rèn)值需要在模板中渲染,需要額外添加配置
// vite.config.js文件中
export default defineConfig({
plugins: [vue({
reactivityTransform: true
})]
})

2. 子傳父 defineEmits
父組件中
<script setup lang="ts">
import { ref } from 'vue';
import MyComVue from './components/MyCom.vue';
let money = ref(100)
const event1 = (val: number) => {
console.log('event1',val);
money.value = val
}
const changeCar = (val: string) => {
console.log('changeCar',val);
}
</script>
<template>
<div style="padding: 20px; margin: 20px; border: 1px solid red">
<h1>父組件</h1>
<p>傳給子組件:{{money}}</p>
<MyComVue
:money="money"
car="特斯拉"
@change-car="changeCar"
/>
<MyComVue
:money="money"
@event1="event1"
/>
</div>
</template>
子組件中
<script setup lang="ts">
// 使用ts的泛型指令props類型
const {money, car='GTR'} = defineProps<{
money: number
car?:string
}>()
// js中-- const myEnit = defineEmits(['event1'])
// ts中
const myEmit = defineEmits<{
(e:'event1', money:number):void
(e:'changeCar', val:string):void
}>()
const hClick = () => {
myEmit('event1', 200)
myEmit('changeCar', 'BWM')
}
</script>
<template>
<div style="padding: 20px; margin: 20px; border: 1px solid red">
<h1>子組件</h1>
<p>從父組件接收 {{money}} {{car}}</p>
<button @click="hClick">emit</button>
</div>
</template>

3. ref和computed
<script setup lang="ts">
import {computed, ref} from 'vue'
// 1. ref<泛型>()
// 簡單類型可以省略,復(fù)雜類型推薦使用
// const todos = ref([{id:1, content: 'sleep', isDone: true}])
// ref<{id:Number,content: String,sDone: Boolean}[]>([])
const todos = ref<{
id:Number
content: String
isDone: Boolean
}[]>([])
setTimeout(()=>{
todos.value = [
{id:1, content: 'sleep', isDone: true},
{id:2, content: 'work', isDone: false}
]
},1000)
// 2. 計算屬性: 已完成數(shù)量
// 通過泛型可以指定computed計算屬性的類型,通常可以省略
const leftCount = computed(() => {
return todos.value.filter(item => item.isDone).length
})
</script>
<template>
<div>
<ul>
<li v-for="item in todos">{{item.content}} {{item.isDone}}</li>
</ul>
已完成: {{leftCount}}
</div>
</template>

4. 事件處理 ($event)
$event在vue中,他是一個特殊的變量名
- 1. 寫在回調(diào)函數(shù)中
- 2. 固定名字
- 3. 表示當(dāng)前的事件對象
const move = (e: MouseEvent) => {
mouse.value.x = e.pageX
mouse.value.y = e.pageY
}
<-- 鼠標(biāo)懸停在 $event 上會提示類型為 MouseEvent -->
<h1 @mousemove="move($event)">根組件</h1>
5. Template Ref
<template>
<div>
<h1 ref="refH1">ref</h1>
<!-- 點(diǎn)擊按鈕在控制臺打印 H1 的中的value值 -->
<button @click="hClick">click</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const refH1 = ref<null | HTMLHeadElement>(null)
const hClick = () => {
console.log(refH1.value?.innerHTML);
}
</script>
6. 可選鏈操作符
可選鏈操作符( ?. )允許讀取位于連接對象鏈深處的屬性的值,而不必明確驗證鏈中的每個引用是否有效。
let nestedProp = obj.first?.second;
console.log(res.data?.data)
obj.fn?.()
if (obj.fn) {
obj.fn()
}
obj.fn && obj.fn()
// 等價于
let temp = obj.first;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
7.非空斷言
如果我們明確的知道對象的屬性一定不會為空,那么可以使用非空斷言 !
// 告訴typescript, 明確的指定obj不可能為空 let nestedProp = obj!.second;
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue無法訪問.env.development定義的變量值問題及解決
這篇文章主要介紹了Vue無法訪問.env.development定義的變量值問題及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01
vue3中使用viewerjs實現(xiàn)圖片預(yù)覽效果的項目實踐
viewer.js是一款開源的圖片預(yù)覽插件,功能十分強(qiáng)大,本文主要介紹了vue3中使用viewerjs實現(xiàn)圖片預(yù)覽效果的項目實踐,具有一定的參考價值,感興趣的可以了解一下2023-09-09
vue3?+?Ant?Design?實現(xiàn)雙表頭表格的效果(橫向表頭+縱向表頭)
這篇文章主要介紹了vue3?+?Ant?Design?實現(xiàn)雙表頭表格(橫向表頭+縱向表頭),需要的朋友可以參考下2023-12-12
vue組件引用另一個組件出現(xiàn)組件不顯示的問題及解決
這篇文章主要介紹了vue組件引用另一個組件出現(xiàn)組件不顯示的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04

