如何在vue.js中从循环外获取v-for循环数据



我有一个表格,显示产品名称、数量、价格和总价。我已经把总成本的逻辑写成了公式成本*数量。我在表外有一个按钮,默认情况下使用v-if指令将其隐藏。如果只有一个产品数量大于零,我如何使该按钮处于活动状态。默认情况下,我给出了0作为数量,因为它会根据用户的不同而变化。我在v-for循环中有一个产品数组,迭代为v-for="产品中的p",所以数量将是p.quantity。我如何从循环外使用该p.quantities

## Html table ##
<table class="table table-striped">
<thead>
<tr>
<td>S.No#</td>
<td>Product</td>
<td>Cost</td>
<td>Quantity</td>
<td>Total</td>
</tr>
</thead>
<tbody>
<tr v-for="p in products">
<td>1</td>
<td>{{p.item}}</td>
<td>{{p.cost}}</td>
<td><input type="number" class="form-control qty-box" name="" v-model='p.qt'  min="0"></td>
<td>{{p.cost*p.quantity}}</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-md-12">
<center v-if="btn"><button class="btn btn-success">Confirm</button></center>
</div>
</div>
## Vue-cli Code ##
<script>
export default {
name: 'app',
data () {
return {
btn:false,
counter:8,
qty:0,
proTotal:'',
products:[
{'item':'timber','cost':250,'id':1, 'quantity ':0},
{'item':'wood','cost':240,'id':2, 'quantity ':0},
{'item':'primer','cost':120,'id':3, 'quantity ':0},
{'item':'plywood','cost':360,'id':4, 'quantity ':0},
{'item':'marker','cost':220,'id':5, 'quantity ':0},
{'item':'roughwood','cost':480,'id':6, 'quantity ':0},
],
msg: 'Counter',
}
},
mounted:function(){
this.bill();
},
methods:{
bill(){
this.qty = this.p.quantity;
if(this.qty>0){
btn:true;
}
}
}
}
</script>

这是计算属性的一个很好的用例:

computed: {
showButton() {
var showButton = false;
this.products.forEach(product => {
if (product.quantity > 0) {
showButton = true;
}
});
return showButton;
}
}

此外,您必须将number添加到v-model,这样它就不会存储为字符串。

你的整个代码看起来是这样的:

<template>
<div id="about">
<table class="table table-striped">
<thead>
<tr>
<td>S.No#</td>
<td>Product</td>
<td>Cost</td>
<td>Quantity</td>
<td>Total</td>
</tr>
</thead>
<tbody>
<tr v-for="(p, index) in products" :key="index">
<td>1</td>
<td>{{p.item}}</td>
<td>{{p.cost}}</td>
<td><input type="number" class="form-control qty-box" name="" v-model.number='p.quantity' min="0"></td>
<td>{{p.cost*p.quantity}}</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-md-12">
<p v-if="showButton">
<button class="btn btn-success">Confirm</button>
</p>
</div>
</div>
</div>
</template>
<script>
export default {
name: "app",
data() {
return {
btn: false,
counter: 8,
qty: 0,
proTotal: "",
products: [
{ item: "timber", cost: 250, id: 1, quantity: 0 },
{ item: "wood", cost: 240, id: 2, quantity: 0 },
{ item: "primer", cost: 120, id: 3, quantity: 0 },
{ item: "plywood", cost: 360, id: 4, quantity: 0 },
{ item: "marker", cost: 220, id: 5, quantity: 0 },
{ item: "roughwood", cost: 480, id: 6, quantity: 0 }
],
msg: "Counter"
};
},
computed: {
showButton() {
var showButton = false;
this.products.forEach(product => {
if (product.quantity > 0) {
showButton = true;
}
});
return showButton;
}
}
};
</script>

相关内容

  • 没有找到相关文章

最新更新