不确定我完全理解你的要求,但看看下面的内容:
编辑
更新为使用Vuex – 但不是通过v模型,因为它不会调用所需的突变或操作
const store = new Vuex.Store({
state: {
products: [
{
name: 'foo',
quantity: 0,
},
{
name: 'bar',
quantity: 0,
},
],
},
getters: {
cart (state) {
return state.products.filter((product) => {
return product.quantity > 0
})
},
},
mutations: {
updateQuantity(state, payload) {
state.products[payload.index].quantity = payload.val
},
}
})
new Vue({
el: '#app',
computed: {
products() {
return store.state.products
},
cart() {
return store.getters.cart
},
},
methods: {
addItem (index, val) {
store.commit('updateQuantity', { index, val })
},
}
})
{{ product.name }}
0
{{n}}
cart
{{ cart }}