写在前面
package.json
“dependencies”: {
“vue”: “^3.4.31”
},
“devDependencies”: {
“@vitejs/plugin-vue”: “^5.0.5”,
“typescript”: “^5.2.2”,
“vite”: “^5.3.4”,
“vue-tsc”: “^2.0.24”
}
1. 父传子
// Father 组件
// 父传子
<script setup lang="ts">
import Son from './components/Son.vue'
// 父传子
const msg: string = 'Hello World'
// 子组件向父组件传递数据
const sonHandler = (msg: string) => {
console.log('father收到了:' + msg)
}
</script>
<template>
<div>
<Son :msg="msg" @sonHandler="sonHandler" />
<!-- <Son /> -->
</div>
</template>
// Son组件
<template>
<div>
<h3>我是子组件 {{ msg }}</h3>
<button type="button" @click="handleClick">
点击接收子组件数据
</button>
</div>
</template>
<script setup lang="ts">
// 父传子
// 非TS语法
/* defineProps({
msg: {
type: String,
default: '我是默认值'
}
}) */
// TS语法
type Props = {
msg?: string
description?: string
}
// 默认值操作
// 低版本Vue不建议使用
const a = withDefaults(defineProps<Props>(), {
msg: '我是默认值',
description: '我是默认描述'
})
// console.log(a)
// 非TS语法 子传父
/* const emit = defineEmits(['sonHandler'])
const handleClick = () => {
emit('sonHandler', '大别墅')
} */
// TS语法 子传父
const emit = defineEmits<{
// Vue3.3以前的写法
// (e: 'sonHandler', msg: string): void
// Vue3.3以后的写法
sonHandler: [msg: string]
}>()
const handleClick = () => {
emit('sonHandler', '大别墅')
}
</script>
2. Ref 与 Computed 的使用
<template>
<div>
{{ msg }}
</div>
<div v-for="item in list" :key="item.id">
{{ item.id }} --- {{ item.name }}
</div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
const msg = ref<number>(0)
type Todo = { id: number, name: string }[]
const list = ref<Todo>([
{
id: 1,
name: 'test'
},
{
id: 2,
name: 'test2'
}
])
// 计算属性 ==> 在绝大多数的时候,都不需要手动指定类型,会类型推断
const leftCount = computed(() => {
return list.value.length
})
</script>
3. 事件类型处理
// 事件类型
const handleClick = (e: MouseEvent) => {
console.log(e.pageX, e.pageY)
}
1. TypeScript 类型声明文件
由于第三方包最终都会打包成 js 文件,就会丧失 TS 的类型特性
所以这些第三方库都会提供一个.d.ts
结尾的类型声明文件,来告诉开发者这个库所拥有的所有类型
补充:
第三方库可能没有提供类型声明文件(jquery, lodash),那我们将无法正常在 TS 中使用,就需要自行下载第三方提供的类型声明文件。
@types/xxxx
这里来找
2. 自定义类型声明文件 - 共享数据
综合案例
案例源码地址: https://gitee.com/wei-zhou-abc/tsxuexilicheng