组件使用:
和Vue2.0不同,2.0使用组件是要在components属性中注册组件;在Vue3.0中只需要在script标签中导入组件就可以使用了,不需要再注册组件
计算属性
用法:基本用法和vue2.0没什么区别,但是不用再都写在computed对象中,只需要再下那个要计算的函数前添加computed().
注意引用对象arr要用reactive函数,实现响应式数据
<script setup>
import { reactive, computed } from "vue"
let arr = reactive([
{ name: "菜名1", price: 20, count: 3 },
{ name: "菜名2", price: 10, count: 1 },
{ name: "菜名3", price: 2, count: 5 },
{ name: "菜名4", price: 45, count: 7 }
])
let total = computed(() => {
return arr.reduce((n1, n2) => (
n1 + n2.price * n2.count
), 0)
})
let add=(index)=>{
arr[index].count++
}
let sub=(index)=>{
arr[index].count--
}
</script>
<template>
<div class="Box">
<div v-for="(el,index) in arr" class="name" :key="index">
<span>菜名:{{el.name}}----- 价格:{{el.price}}----- 数量</span>
<button @click="sub(index)">-</button>
<span>{{el.count}}</span>
<button @click="add(index)">+</button>
</div>
<button>总价:{{total}}元</button>
</div>
</template>