1.计算属性具有缓存特性,在computed中的响应式数据不发生变化时,就不重新加载computed中的逻辑。(作用于大量耗时的逻辑解构,并为其数据不经常发生变化,可采取computed计算属性提高程序效率-->常用于购物车数据计算)
代码如下:
html
<script>
import { computed, ref } from "vue";
export default {
setup() {
const people = ref(["你是好人", "你不是好人"]);
const config = ref(true);
console.log(people);
const num = ref(0);
const shop = ref([
{ id: 1, name: "苹果", price: 3, num: 2 },
{ id: 2, name: "香蕉", price: 4, num: 1 },
]);
const totalPrice = computed(() => {
let prices = 0;
shop.value.forEach((item) => {
prices += item.price * item.num;
});
console.log("用来检测响应式数据的变化");
return prices;
});
return {
people,
config,
totalPrice,
shop,
num,
};
},
};
</script>
<template>
<option value="苹果">苹果</option>
<option value="香蕉">香蕉</option>
<option value="橘子">橘子</option>
</select>
<h2>你选择的水果是:{{ fruit }}</h2> -->
<!-- <h2 v-show="people">{{ people }}</h2> -->
<button @click="config = config ? !config : !config">点击切换人设</button>
<p v-show="config">{{ people[0] }}</p>
<p v-if="config">{{ people[0] }}</p>
<p v-else>{{ people[1] }}</p>
<div v-for="item in shop" :key="item.id">
<p>商品:{{ item.name }}</p>
<p
@click="
() => {
const goods = shop.find((obj) => obj.title == item.title);
goods.price++;
}
"
>
{{ item.price }}元/斤
</p>
<p
@click="
() => {
const goods = shop.find((obj) => obj.title == item.title);
goods.num++;
}
"
>
{{ item.num }}个
</p>
</div>
<p>总价: {{ totalPrice }}</p>
<P>{{ num }}</P>
<button @click="num++">num++</button>
</template>
通过F12检测数据变化: