TypeScript与Vue
Article directory
Reference link: https://vuejs.org/guide/typescript/composition-api.html
With vue3 and ts, an additional vscode plugin needs to be installed: Typescript Vue Plugin
defineProps与Typescript
Goal: Master how defineProps works with ts
- defineProps cooperates with Vue's default syntax for type verification (runtime declaration)
// 运行时声明
defineProps({
money: {
type: Number,
required: true
},
car: {
type: String,
required: true
}
})
- defineProps cooperates with ts generics to define props type verification, which is more direct
// 使用ts的泛型指令props类型
defineProps<{
money: number
car?: string
}>()
- props can be destructured to specify default values
<script lang="ts" setup>
// 使用ts的泛型指令props类型
const {
money, car = '小黄车' } = defineProps<{
money: number
car?: string
}>()
</script>
If the provided default value needs to be rendered in the template, additional configuration needs to be added
https://vuejs.org/guide/extras/reactivity-transform.html#explicit-opt-in
// vite.config.js
export default {
plugins: [
vue({
reactivityTransform: true
})
]
}
defineEmits与Typescript
Goal: Master how defineEmit works with ts
- defineEmits with runtime declaration
const emit = defineEmits(['change', 'update'])
- defineEmits cooperates with the ts type declaration to achieve finer-grained verification
const emit = defineEmits<{
(e: 'changeMoney', money: number): void
(e: 'changeCar', car: string): void
}>()
refs and Typescript
Goal: Master how to use ref with ts
- Specify the value type of value through generics, if it is a simple value, this type can be omitted
const money = ref<number>(10)
const money = ref(10)
- If it is a complex type, it is recommended to specify a generic type
type Todo = {
id: number
name: string
done: boolean
}
const list = ref<Todo[]>([])
setTimeout(() => {
list.value = [
{
id: 1, name: '吃饭', done: false },
{
id: 2, name: '睡觉', done: true }
]
})
reactive与Typescript
Goal: Master how to use reactive with typescript
// reactive 适合于明确属性的对象场景
type User = {
name: string
age: number
};
const obj: User = reactive({
name: "zs",
age: 18
});
computed与Typescript
Goal: Master how to use computed with typescript
- The type of computed property can be specified through generics, which can usually be omitted
const leftCount = computed<number>(() => {
return list.value.filter((item) => item.done).length
})
console.log(leftCount.value)
Event handling with Typescript
Goal: Master how to use event handlers with typescript
const move = (e: MouseEvent) => {
mouse.value.x = e.pageX
mouse.value.y = e.pageY
}
<h1 @mousemove="move($event)">根组件</h1>
Template Ref与Typescript
Goal: Master how to use Typescript when ref operates DOM
const imgRef = ref<HTMLImageElement | null>(null)
onMounted(() => {
console.log(imgRef.value?.src)
})
How to view the type of a DOM object: view it through the console
document.createElement('img').__proto__
optional chaining operator
Goal : Master the optional chain operator syntax provided in js
content
- The optional chaining operator (
?.
) allows reading the value of a property located deep in a chain of connection objects without having to explicitly verify that each reference in the chain is valid. - Reference document: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining
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);
non-null assertion
Goal : Master the usage syntax of non-empty assertions in ts
content:
- If we clearly know that the properties of the object must not be empty, then we can use non-null assertion
!
// 告诉typescript, 明确的指定obj不可能为空
let nestedProp = obj!.second;
- Note: Non-empty assertions must ensure that this attribute can be used, otherwise using non-empty assertions will cause bugs