老师,我有这么个设想,比如我有多个商品,我制作了一个商品模板,在添加商品的时候,实时显示总金额。那么这个ref的名字肯定不能一样,应该怎么处理?
<div id="app">
<template v-for="(goods, index) in goodsList">
<goods :ref="'goods'+index" :name="goods.goodsName"
:price="goods.goodsPrice"
@inc="add" @dec="red"></goods>
</template>
<h1>商品总共:{{total}}元</h1>
</div>
<script type="text/javascript">
Vue.component('goods', {
props: ["name", "price"],
template: "<div><button @click='dec'>-</button>{{name}},价格:{{price}}<button @click='inc'>+</button></div>",
methods: {
dec() { this.$emit('dec')},
inc() { this.$emit('inc')}
}
});
let vm = new Vue({
el: "#app",
data: {
goodsList: [{
goodsName: "小米10",
goodsPrice: 4999
}, {
goodsName: "苹果12",
goodsPrice: 9999
}, {
goodsName: "华为p40",
goodsPrice: 5999
}],
total: 0
},
methods: {
add() {
console.log(this.$refs)
},
red() {}
}
})
</script>
代码还没写完,因为到ref这里不知道怎么处理了。
课程紧跟Vue3版本迭代,企业主流版本Vue2+Vue3全掌握
了解课程