Reputation: 59
I have a form used to post product in a shopping cart, I have a Vuejs component setup and it retrieves data just fine, but when I try adding a select tag, I can't pass the data from it. Here's my code for the blade.php file:
<form action="{{ url('/cart') }}" method="POST" class="side-by-side">
<input type="hidden" name="id" v-model="this.id" value="{{ $product->id }}">
<input type="hidden" name="name" v-model="this.name" value="{{ $product->name }}">
<input type="hidden" name="price" v-model="this.price" value="{{ $product->price }}">
{{-- Can't figure out how to pass the following --}}
<select v-model="selected" required>
<option disabled value="">Please select one</option>
@foreach($product->withOptions() as $option)
<option value="{{ $option->options }}">{{ $option->options }}</option>
@endforeach
</select>
<addToCart :product="{{ $product }}"></addToCart>
and here's my vue file:
export default {
props: ['product'],
data() {
return {
id: this.product.id,
quantity: 1,
name: this.product.name,
price: this.product.price,
selected: '' // always null, can't figure it out
}
},
methods: {
addtocart() {
axios.post('/cart/', this.$data)
.then(flash(this.product.name + ' was added to cart'));
}
}
}
Thank you for your help.
Upvotes: 2
Views: 1675
Reputation: 95
try this:
<select v-model="selected" required>
<option disabled value="">Please select one</option>
<option v-for="option in product" v-bind:value="product.option">{{product.option}}</option>
</select>
Upvotes: 1
Reputation: 59
Solved that way:
<addToCart :product="{{ $product }}" :selected="selected"></addToCart>
And in the vue file :
export default {
props: ['product', 'selected'],
data() {
return {
id: this.product.id,
quantity: 1,
name: this.product.name,
price: this.product.price,
options: this.selected
}
},
watch: {
selected: function() {
return this.options = this.selected
}
},
methods: {
addtocart() {
axios.post('/cart/', this.$data)
.then(flash(this.product.name + ' was added to cart'));
},
Just added a watcher thing.
Upvotes: 1
Reputation: 2408
In your blade.php file
<addToCart :product="{{ $product }}" :selected="selected" ></addToCart>
Now in your Vue component, you can access the value of selected like this
export default {
props: ['product','selected'],
data() {
return {
id: this.product.id,
quantity: 1,
name: this.product.name,
price: this.product.price,
selected: this.selected
}
},
methods: {
addtocart() {
self= this;
axios.post('/cart/',{
id : self.id,
quantity: self.quantity,
name: self.name,
price: self.price,
selected: self.selected
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
})
}
}
}
Upvotes: 0