Reputation: 769
I want to have v-model
and value
set in one input. Here is my code:
<td>
<input v-model="invoice.items[n-1].net_price" type="number" step="0.01" min="1" form="invoice-form">
</td>
<td v-if="invoice.items[n-1].net_price && invoice.items[n-1].quantity">
<input :value="(invoice.items[n-1].net_price * invoice.items[n-1].quantity).toFixed(2)" type="text" form="invoice-form" readonly>
</td>
<td v-else>
<input type="text" readonly>
</td>
Problem is with 2nd input. Now it works like this:
net-price
inputreadonly
inputNow I want to set v-model
in this 2nd input, but when I try to do this I get an error.
Is there a way to set a model to this calculated value?
Upvotes: 0
Views: 112
Reputation: 9200
A more robust approach is to perhaps put your calculation logic in a method and use destructuring assignment to unpack the values off the individual items. In addition, the variables can also be assigned default values in the case that the unpacked values are undefined
-- That way, you no longer need to worry about the computed values returning NaN
since they will fallback to zeros when they are.
Try something like that:
new Vue({
data: () => ({
invoice: {
items: [
{
net_price: 30.05,
quantity: 4
},
{
net_price: 14.99,
quantity: 7
},
]
}
}),
methods: {
calculate({ net_price = 0, quantity = 0}) {
return (net_price * quantity).toFixed(2);
}
}
})
.$mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<form id="invoice-form">
<table>
<thead>
<tr>
<th>Net Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) of invoice.items" :key="index">
<td>
<input v-model="item.net_price" type="number" step="0.01" min="1" form="invoice-form" />
</td>
<td>
<input v-model="item.quantity" type="number" min="0" form="invoice-form" />
</td>
<td>
<input :value="calculate(item)" form="invoice-form" readonly />
</td>
</tr>
</tbody>
</table>
</form>
</div>
Upvotes: 2