Vue.js - 从模态获取数据并保存到数组



我有一个包含来自 Vue.js 数据的模态,我想完成的是,每当单击"添加购物车"按钮时,模态内的数据都会保存到 vue 内的另一个数组(itemCart(中。

Vue.js:

new Vue({
el: '#item-data',
data () {
return {
data:[],
selectedUser:'',
itemCart: ''
}
},
mounted () {
axios.get('api link here', {
headers : {
Authorization: 'Bearer ' + access_token
},
params: {
limit: 250
}
})
.then((response) => {
// handle success
this.data = response.data.items
removeLoader();
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
},
methods:{
sendInfo(items) {
this.selectedUser = items;
},
addCart: function(cartItems){
this.itemCart.push({cartItems});
console.log(cartItems);
}
}
})

模 态:

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<a href="#" class="latest-product__item">
<div class="latest-product__item__pic">
<img src="img/item_image_placeholder.jpg" alt="">
</div>
<div class="latest-product__item__text">
<span>{{selectedUser.item_name}}</span>
<div v-for="variant in selectedUser.variants">
<h6>Php {{variant.default_price}}/piece</h6>
</div>
<div class="product__details__quantity">
<div class="quantity">
<div class="pro-qty">
<input type="text" value="1">
</div>
</div>
</div>
</div>
</a>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success btn-block" @click="addCart">Add to Cart</button>
</div>
</div>
</div>
</div>

我尝试将 v-model 放置在模态的输入标签内,但我收到一个错误,说它未在实例上定义。 我如何实现这一点?

您需要在模态上添加一个方法(内联或在methods键中(,该方法专门执行您想要的操作。

只是粗略地了解我的意思:

<button 
type="button" 
class="btn btn-success btn-block" 
@click="() => addCart( {
item_name: selectedUser.item_name,
price: variants.default_price,
})"
>Add to Cart</button>

显然,你必须使用它来让它做你想做的事。

最新更新