IT이야기

v-for 및 v-model을 사용한 vuex 계산 속성이 포함된 Vue js

cyworld 2022. 4. 23. 10:28
반응형

v-for 및 v-model을 사용한 vuex 계산 속성이 포함된 Vue js

v-for를 v-model과 함께 사용해야 해.문서를 읽었는데 돌연변이 처리기 밖에서 돌연변이를 수행하지 않고 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를 사용하도록 업데이트됨 - 필요한 돌연변이 또는 작업을 호출하지 않으므로 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>

참조URL: https://stackoverflow.com/questions/40913456/vue-js-with-vuex-computed-properties-with-v-for-and-v-model

반응형