本文主要是介绍05 vue3之computed用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
computed用法
计算属性就是当依赖的属性的值发生变化的时候,才会触发他的更改,如果依赖的值,不发生变化的时候,使用的是缓存中的属性值。
1 函数形式
let name = computed(() => {return one.value + "---" + two.value; // 取值一定要加.value
});
2 对象形式
let name1 = computed({get() {return one.value + "---" + two.value;},set() {one.value + "---" + two.value;},
});
完整案例
<template><input v-model="one" type="text" /><input v-model="two" type="text" /><!-- <div>{{ one }}---{{ two }}</div> --><div>{{ name }}</div><div>{{ name1 }}</div></template><script setup lang="ts">
import { ref, reactive, computed } from "vue";
let one = ref("");
let two = ref("");
// 1种写法 函数式写法 不允许修改值
let name = computed(() => {return one.value + "---" + two.value; // 取值一定要加.value
});
// 2种写法 选项式写法 允许修改值
let name1 = computed({get() {return one.value + "---" + two.value;},set() {one.value + "---" + two.value;},
});</script><style scoped>
table,
td {border: 1px solid #333;
}thead,
tfoot {background-color: #333;color: #fff;
}
</style>
购物车案例:
能优化代码 减少多次调用
<template><table><inputplaceholder="请输入名称"v-model="keyWord"type="text"/><thead><tr><!-- <th colspan="2">The table header</th> --><th>名称</th><th>数量</th><th>价格</th><th>操作</th></tr></thead><tbody><tr v-for="item in searchData" :key="item"><td>{{ item.name }}</td><td><button @click="add(item, true)">+</button>{{ item.num}}<button @click="add(item, false)">-</button></td><td>{{ item.price * item.num }}</td><td><button @click="del(index)">删除</button></td></tr></tbody><tfoot><td></td><td></td><td></td><td>总价:{{ $total }}</td></tfoot></table>
</template><script setup lang="ts">
import { ref, reactive, computed } from "vue";
type shop = {name: string;num: number;price: number;
};
let keyWord = ref("");// let $total = ref<string>("0");
let data = reactive<shop[]>([{ name: "裤子", num: 1, price: 100 },{ name: "衣服", num: 1, price: 200 },{ name: "鞋子", num: 1, price: 300 },
]);
const searchData = computed(() => {return data.filter((item) =>item.name.includes(keyWord.value));
});let add = (item: shop, type: Boolean): void => {if (item.num < 99 && type) {item.num++;// total();}if (item.num > 1 && !type) {item.num--;// total();}
};
let del = (index: number) => {data.splice(index, 1);// total();
};/* const total = () => {$total.value = data.reduce((pre, next) => {return pre + next.price * next.num;}, 0);
}; */
// total();// 可以看到total被调用了很多次 我们可以使用computed优化代码
const $total = computed(() => {return data.reduce((pre, next) => {return pre + next.price * next.num;}, 0);
});
</script><style scoped>
table,
td {border: 1px solid #333;
}thead,
tfoot {background-color: #333;color: #fff;
}
</style>
这篇关于05 vue3之computed用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!