TypeScript在vue中的使用解读

主要介绍 TypeScript 在 vue 中的使用,还有一些j注释起来的 js 代码做对照

参考链接:合成 API 的TypeScript

vue3中配合使用TS,还需要额外安装一个vscode插件:Typescript Vue Plugin

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可以通过解构来指定默认值,将指定默认值的变量定义为可选参数
 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>

computedr

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. 计算属性: 已完成数量
 // 通过泛型可以指定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>

computed

4. 事件处理 ($event)

$event在vue中,他是一个特殊的变量名

  • 1. 写在回调函数中
  • 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;

总结

作者:霞霞要乖原文地址:https://blog.csdn.net/weixin_67340539/article/details/125745966

%s 个评论

要回复文章请先登录注册