简体   繁体   English

Vue js与vuex计算属性与v-for和v-model

[英]Vue js with vuex computed properties with v-for and v-model

I need to use v-for with v-model. 我需要使用v-for v-model。 I read the docs and there is no example of how to use it with v-for without performing mutation outside the mutation handler. 我阅读了文档 ,没有关于如何在不使用突变处理程序之外的突变的情况下将其与v-for一起使用的示例。

How can I use v-model inside v-for without mutating the property directly? 如何在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
    })
  },

Not sure I completely understood what you're asking but have a look at the below: 不确定我完全理解你的要求,但看看下面的内容:

EDIT 编辑

Updated to use Vuex - but not via v-model as that wouldn't be calling a mutation or action which is required 更新为使用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 }) }, } }) 
 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM