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)來指定默認值,將指定默認值的變量定義為可選參數(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>
注:提供的默認值需要在模板中渲染,需要額外添加配置
// 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<泛型>()
// 簡單類型可以省略,復雜類型推薦使用
// 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. 表示當前的事件對象
const move = (e: MouseEvent) => {
mouse.value.x = e.pageX
mouse.value.y = e.pageY
}
<-- 鼠標懸停在 $event 上會提示類型為 MouseEvent -->
<h1 @mousemove="move($event)">根組件</h1>
5. Template Ref
<template>
<div>
<h1 ref="refH1">ref</h1>
<!-- 點擊按鈕在控制臺打印 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-cli4.x創(chuàng)建企業(yè)級項目的方法步驟
這篇文章主要介紹了vue-cli4.x創(chuàng)建企業(yè)級項目的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06
vue實現(xiàn)動態(tài)數(shù)據(jù)綁定
本篇文章主要介紹了vue實現(xiàn)動態(tài)數(shù)據(jù)綁定,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04
詳解Vue-Cli 異步加載數(shù)據(jù)的一些注意點
本篇文章主要介紹了詳解Vue-Cli 異步加載數(shù)據(jù)的一些注意點,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
vue3+ElementPlus使用lang="ts"報Unexpected?token錯誤的解決
最近開發(fā)中遇到了些問題,跟大家分享下,這篇文章主要給大家介紹了關(guān)于vue3+ElementPlus使用lang="ts"報Unexpected?token錯誤的解決辦法,需要的朋友可以參考下2023-01-01

