Vue3—计算属性computed的使用

5,873 阅读1分钟

1.什么是computed

computed 表示计算属性,通常用于处理数据,简化书写在模板中的复杂逻辑。使用 computed 可以将数据处理成我们想要的格式,无需在模板中使用复杂冗长的计算表达式。

computed有两个方法,分别是set()和get()。它可以接受一个带有 get 和 set 函数的对象来创建一个可写的 ref 对象。

2.computed的使用

1)定义路由:

<!--routers/router.ts-->
{
      path: '/test',
      name: 'test',
      component: () => import('~/views/test/index_computed.vue'),
      meta: {
        title: '测试computed'
      }
    }

2)编写代码:

示例一:

<!--views/test/index_computed.vue-->
<template>
  <div>{{ reverseMsg }}</div>   //dlrowolleh
</template>

<script setup lang='ts'>
import { ref, reactive, computed } from "vue";    //1.引入computed
const msg = ref("helloworld");
const reverseMsg = computed(() => {
       return msg.value.split("").reverse().join("");    //dlrowolleh
});

示例2:

<!--views/test/index_computed.vue-->
<template>
  <div>{{ plus }}</div>      <!-- 8,触发plus1里的set函数 -->  
  <div>{{ count1 }}</div>    <!-- 3,触发plus1里的set函数 -->
  <div>{{ plus1 }}</div>     <!-- 6,触发plus1里的get函数 -->
</template>

<script setup lang='ts'>
// 创建一个只读的计算属性ref对象
const count = ref(4);
const plus = computed(() => {
  return count.value * 2;        //8,此处只读取了count变量里的值
});

// 创建一个可写的计算属性ref对象。默认下触发get函数,set函数会将声明的变量值进行重置
const count1 = ref(4);
const plus1 = computed({
  get: () => count1.value * 2,  //4)打印plus1,再次触发get函数时,count1.value的值是新赋予的3,所以plus1的值为6,而非8
  set: (val) => {              //2)触发plus1里的set函数
    count1.value = val - 1;    //3)count1.value的值由4-->3
  }
});
plus1.value = 4;               //1)将plus1的val值设置为4
</script>

3.为什么要有computed

模板中逻辑过重,不易维护,所以使用计算属性computed来简化书写响应式状态的复杂逻辑。