Vue3 computed 赋值

 1 // 还是这2个数据源
 2 const firstName = ref<string>('Bill')
 3 const lastName = ref<string>('Gates')
 4 
 5 // 这里我们配合setter的需要,改成了另外一种写法
 6 const fullName = computed({
 7   // getter我们还是返回一个拼接起来的全名
 8   get() {
 9     return `${firstName.value} ${lastName.value}`
10   },
11   // setter这里我们改成只更新firstName,注意参数也定义TS类型
12   set(newFirstName: string) {
13     firstName.value = newFirstName
14   },
15 })
16 console.log(fullName.value) // 输出 Bill Gates
17 
18 // 2s后更新一下数据
19 setTimeout(() => {
20   // 对fullName的赋值,其实更新的是firstName
21   fullName.value = 'Petter'
22 
23   // 此时firstName已经得到了更新
24   console.log(firstName.value) // 会输出 Petter
25 
26   // 当然,由于firstName变化了,所以fullName的getter也会得到更新
27   console.log(fullName.value) // 会输出 Petter Gates
28 }, 2000)

 

来自于: https://vue3.chengpeiquan.com/component.html#基本格式

posted @ 2022-07-09 10:10  googlegis  阅读(1275)  评论(0编辑  收藏  举报

坐标合肥,非典型GIS开发人员 GitHub