I am doing a simple calculation in app.js. It just multiplies the product price by quantity. I want to display the total value in laravel, so a user can preview their order.
app.js
const app = new Vue({
el: '#item',
data() {
return {
form: {
price: 0,
quantity: 0,
total: 0
}
}
},
methods: {
updatePrice(event) {
this.form.price = event.target.value;
this.form.total = this.form.price * this.form.quantity
},
updateQuantity(event) {
this.form.quantity = event.target.value;
this.form.total = this.form.price * this.form.quantity
}
}
This is fine. They calculate the form value in blade file. But how I can display the total?
I want to display the ' total
' in blade file. How can I access that? When I use @{{ total }}
I get this error:
app.js:36519 [Vue warn]: Property or method "total" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
Typically you would use template interpolations for that.
Something like {{ form.total }}
, which in a Blade template, to overcome the usage of {{
, it would be:
<div id="item">
<p>Total is: @{{ form.total }}</p>
</div>
Alternatively, you can change Vue's delimiters and workaround this issue. For example ( delimiters: ['!{', '}!'],
):
const app = new Vue({ el: '#item', delimiters: ['!{', '}!'], data() { return { form: { price: 1, quantity: 1, total: 1 } } }, methods: { updatePrice(event) { this.form.price = event.target.value; this.form.total = this.form.price * this.form.quantity }, updateQuantity(event) { this.form.quantity = event.target.value; this.form.total = this.form.price * this.form.quantity } } });
<script src="https://unpkg.com/vue"></script> <div id="item"> <p>Total is: !{ form.total }!</p> price: <input @input="updatePrice"><br> quantity: <input @input="updateQuantity"><br> </div>
Although that would work, in your case, instead of handling events directly, I suggest using v-model
in price
and quantity
and creating total
as a computed property . This would be an approach that better uses Vue's capabilities (and is less code, yay):
const app = new Vue({ el: '#item', data() { return { form: { price: 1, quantity: 1, total: 1 } } }, computed: { total() { return this.form.price * this.form.quantity } } });
<script src="https://unpkg.com/vue"></script> <div id="item"> <p>Total is: {{ total }}</p> price: <input v-model="form.price"><br> quantity: <input v-model="form.quantity"><br> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.