vue3-computed

7/18/2020 vue3

计算属性是依赖得属性值发生变化的时候才会触发他的更新,如果依赖得值不发生变化,则使用缓存中的属性值。

# 函数形式


返回一个不可变的响应式 ref 对象

<script setup lang="ts">
import { ref, computed } from 'vue';

let count = ref<number>(0)

let newCount = computed<number>(() => count.value + 1 )

console.log(newCount.value); // 1
newCount.value ++  // 报错 Write operation failed: computed value is readonly

</script>

<template>
  <div>
   
  </div>
</template>

<style scoped>
</style>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 对象形式


具有 get 和 set 函数的对象,用来创建可写的 ref 对象。

<script setup lang="ts">
import { ref, computed } from 'vue';

let count = ref<number | string>(0)

let newCount = computed({
    get(){
      return count.value
    },
    set(val){
      count.value = "更新了" + val
    }
})


const handleClick = () => {
  newCount.value = 100
}

</script>

<template>
  <div>
    {{newCount}}
    <button @click="handleClick">更新</button>
  </div>
</template>

<style scoped>
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
更新: 7/25/2022, 3:15:19 PM