【问题标题】:Vue js with vuex computed properties with v-for and v-model具有 v-for 和 v-model 的 vuex 计算属性的 Vue js
【发布时间】:2017-04-16 06:10:33
【问题描述】:

我需要将 v-for 与 v-model 一起使用。我阅读了docs 并且没有示例说明如何将它与 v-for 一起使用而不在突变处理程序之外执行突变。

如何在不直接改变属性的情况下在 v-for 中使用 v-model?

  <div v-for="product in products">
     <select @change="addItem(product)" v-model="product.quantity">
        <option value="">0</option>
        <option v-for="n in 10">{{n}}</option>
      </select>
  </div>

 // component

  methods : {
    ...mapMutations({
      addToCart: ADD_TO_CART
    })
  },

【问题讨论】:

  • 您遇到的错误是什么,可以创建它吗?
  • 不要在突变处理程序之外改变 vuex 存储状态
  • 不,你只能通过突变改变 vex 状态。
  • 那么如何使用 v-for 来做到这一点?

标签: javascript vue.js vuex


【解决方案1】:

不确定我是否完全理解您的要求,但请查看以下内容:

编辑

更新为使用 Vuex - 但不是通过 v-model,因为这不会调用所需的突变或操作

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 })
        },
    }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@next"></script>
<div id="app">
    <div v-for="(product, index) in products">
        <label>{{ product.name }}</label>
        <select @change="addItem(index, $event.target.value)">
            <option value="">0</option>
            <option v-for="n in 10">{{n}}</option>
        </select>
    </div>
    <h1>cart</h1>
    <pre>{{ cart }}</pre>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2021-12-18
    • 2018-06-13
    • 2020-04-17
    • 2020-07-01
    相关资源
    最近更新 更多