【Vue3】computed 计算属性

computed 计算属性


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

computed 基础用法

Vue3中有两种写法

  1. 如果计算属性不需要修改,可以直接使用函数形式
  2. 如果计算属性有被修改的情况,则使用对象包括getter和setter方法,get为读取计算属性时触发,set为修改计算属性时触发
    // 响应式源对象
    let person = reactive({
      firstName: "张",
      lastName: "三",
    });
    // 计算属性-简写形式(函数形式),没有考虑计算属性被修改的情况
    /* person.fullName = computed(()=>{
          return person.firstName + '-' + person.lastName
        }) */

    // 计算属性-完整(对象形式),考虑读与写
    person.fullName = computed({
      get(){
        return person.firstName + "-" + person.lastName;
      },
      set(value){
        // 通过修改get的依赖,触发get计算重新计算返回
        const nameArr = value.split('-')
        person.firstName = nameArr[0]
        person.lastName = nameArr[1]
      }
    });

3.4+ 更新computed 获取上个值

get用法

<script setup>
import { ref, computed } from 'vue'

const count = ref(2)

// 这个计算属性在 count 的值小于或等于 3 时,将返回 count 的值。
// 当 count 的值大于等于 4 时,将会返回满足我们条件的最后一个值
// 直到 count 的值再次小于或等于 3 为止。
const alwaysSmall = computed((previous) => {
  if (count.value <= 3) {
    return count.value
  }

  return previous
})
</script>

set用法

<script setup>
import { ref, computed } from 'vue'

const count = ref(2)

const alwaysSmall = computed({
  get(previous) {
    if (count.value <= 3) {
      return count.value
    }

    return previous
  },
  set(newValue) {
    count.value = newValue * 2
  }
})
</script>
posted @ 2022-10-30 22:30  wanglei1900  阅读(251)  评论(0)    收藏  举报