[英]Why is this v-bind:value working?
I'm making a basket system using Laravel and Vue. 我正在使用Laravel和Vue制作篮子系统。 I have a data object in my Vue file, cart.js:
我的Vue文件cart.js中有一个数据对象:
data: {
material: {
id: '',
qty: '1',
},
}
And when the 'Add to Basket' button is clicked on the product page, the following function is called: 当在产品页面上单击“添加到购物篮”按钮时,将调用以下功能:
addToBasket: function(){
var that = this;
var item = this.material;
this.$http.post('/api/buy/addToBasket', item).then(response => {
this.basketAddSuccess = true;
}, response => {
//error
});
}
However, this fails with a 500 error, because as far as I can see the id is not being bound to the Vue instance. 但是,此操作失败并显示500错误,因为据我所知,id未绑定到Vue实例。 Here's the view code:
这是视图代码:
<form v-on:submit.prevent="addToBasket(material)">
<input type="hidden" v-model="material.id" v-bind:value="{{ $material->id }}">
<div class="form-group">
<label for="qty">Quantity</label>
<input class="form-control" name="qty" type="number" v-model="material.qty" v-bind:value="1">
</div>
<button class="btn btn-block btn-primary">@{{ buttonText }}</button>
</form>
Laravel is injecting the value correctly as per the rendered code: Laravel根据渲染的代码正确注入值:
<input type="hidden" v-model="material.id" value="1">
But this isn't being bound to Vue. 但这并不限于Vue。 I have tried every permutation of
v-model
and v-bind
(I know that you shouldn't use both on the same input - this is just the last in a long line of attempts) that I can think of but nothing seems to work. 我已经尝试了可以想到的
v-model
和v-bind
每个排列(我知道您不应该在同一个输入上同时使用这-这只是一长串尝试中的最后一次),但似乎没有任何效果。 Help! 救命!
You need to set the value on the data object, not on the template because you're using v-model directive. 您需要在数据对象上而不是模板上设置值,因为您正在使用v-model指令。 You should take a look to this, it explains well how v-model model directive works in background : https://alligator.io/vuejs/add-v-model-support/
您应该看一下,它很好地说明了v模型模型指令在后台的工作方式: https : //alligator.io/vuejs/add-v-model-support/
EDIT 1 : I juste wrote an exemple with multiples materials. 编辑1:我只是写了一个带有多个材料的示例。 I'm not sure if it will help you, anyway :
无论如何,我不确定是否能为您提供帮助:
The template 模板
<template>
<div class="materials">
<form
class="material"
v-for="material in materials"
:key="material.id"
@submit.prevent="addToBasket(material)"
>
<div class="form-group">
<label for="quantity">Quantity</label>
<input type="number" name="quantity" :value="material.qty">
</div>
<button class="btn btn-block btn-primary">@{{ buttonText }}</button>
</form>
</div>
</template>
Javascript, $materials is a Laravel PHP Array of Objects containing id key and quantity key Javascript,$ materials是包含ID键和数量键的Laravel PHP对象数组
export default {
data() {
return {
basketAddSuccess : false,
materials : {!! json_encode($materials) !!}
};
},
methods : {
addToBasket(material) {
this.$http.post('/api/buy/addToBasket', material).then(response => this.basketAddSuccess = true).catch(error => console.log(error))
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.