在 Vue 3 中,计算属性(Computed)是一种基于响应式依赖进行计算并返回结果的功能。它的特点是具有缓存性,即当依赖的响应式状态没有发生变化时,计算属性不会重新计算,从而提高性能。

与vue2不同点:

计算属性在vue3中是以一个方法的形式存在,需要使用时要进行导入再使用

下面我将以普通使用和get、set方式使用来进行举例:

1、普通使用

<template>
    <div>
        总价: {{ count }}
    </div>
</template>

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

    let goods=reactive([
        {title:'毛巾',price:20,count:2},
        {title:'笔记本',price:20,count:3},
        {title:'笔',price:2,count:4},
    ])

    const count=computed(()=>{
        return goods.reduce((pre,cur)=>pre+cur.price*cur.count,0)
    })
</script>

2、get/set方法使用

注意点:数据修改时要注意数据地址是否改变,会影响到数据是否能在页面上双向绑定

<template>
  <div>
    <table border="1">
      <tr>
        <th><input type="checkbox" v-model="selectAll" />全选/全不选</th>
        <th>id</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
      </tr>
      <tr v-for="(item, index) in user" :key="item.id">
        <td><input type="checkbox" v-model="checkList[index]" /></td>
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.age }}</td>
        <td>{{ item.gender }}</td>
      </tr>
    </table>
  </div>
</template>

<script setup>
import { reactive, computed, onMounted,toRefs } from "vue";
let data = reactive({
  user: [
    { id: 1, name: "张三", age: 20, gender: "男" },
    { id: 2, name: "李四", age: 30, gender: "中性" },
    { id: 3, name: "王五", age: 40, gender: "女" },
    { id: 4, name: "老六", age: 50, gender: "未知" },
  ],
  checkList: [],
});
// 解构
const {user,checkList}=toRefs(data)
// 构造数据
onMounted(() => {
    data.checkList=data.user.map(() => false);
});
// 全选/全不选
let selectAll = computed({
  get() {
    return !data.checkList.includes(false);
  },
  set(val) {
    data.checkList=data.checkList.map(()=>val)
  },
});
</script>

<style lang="scss" scoped>
table {
  width: 700px;
  border-collapse: collapse;
}
</style>

 

 

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐