vue3 组合是API 中我们经常使用的 监听函数 computed 和 watch使用
1、computed 里面添加类型
<script setup lang="ts">
import { ref, computed } from 'vue'
const age = ref(18)
// 定义一个Person 接口
interface Person {
age: number
name: string
}
const person = ref<Person>({
age: 18,
name: 'Andy'
})
// 只读的
const params = computed(():Person => {
return {
age: person.value.age,
name: person.value.name
}
})
console.log('===params=', params)
// 可读可写
const paramsA = computed<Person>({
get: () => person.value,
set: () => {
return {
age: person.value.age + 2,
name: person.value.name
}
}
})
</script>
2、watch() 中的类型使用
// 监听单个数据源时候
<script lang="ts" setup>
import { watch } from 'vue'
interface Person {
age: number
name: string
}
const myParams = watch(():Person => person.value, (n:Person, o:Person) => {
console.log('=n===', n, o)
})
const myParamsAA = watch<Person>(():Person => person.value, (n:Person, o:Person): void => {
console.log('=n===', n, o)
})
</script>