vue3.x 计算属性computed

47 阅读1分钟
  • 与vue2.x中computed配置功能一致,当计算属性中使用的变量的值发生改变时,这个函数才会调用
  • 使用之前与ref函数和reactive函数一样需要先引入进来
<script setup>
import { reactive, computed } from 'vue';
const arr = reactive([
    { title: "鱼香肉丝", price: 43, count: 2 },
    { title: "肉末茄子", price: 43, count: 3 },
    { title: "青椒炒肉", price: 23, count: 4 },
    { title: "回锅肉", price: 66, count: 7 }
])
let all = computed(() => {
    return arr.reduce((n1, n2) => {
        return n1 + n2.price * n2.count
    }, 0)
})
function add(index){
    console.log(arr[index]);
		arr[index].count++
	}
</script>
<template>
    <div>
        <div v-for="(el,index) in arr">{{el.title}}--{{el.price}}--
            <button>-</button>
			<span>{{el.count}}</span>
			<button @click="add(index)">+</button>
        </div>
        <h3>总价:{{all}}</h3>
    </div>
</template>