programing

Vuex에서 상태 어레이를 업데이트하는 방법?

prostudy 2022. 5. 15. 23:42
반응형

Vuex에서 상태 어레이를 업데이트하는 방법?

나는 항목을 추가, 삭제 및 편집할 수 있어야 한다.지금까지 나는 추가와 제거만 할 수 있었다.

내 질문은, 더하기 위해, PUSH를 사용하고, 제거하기 위해 SPLICE를 사용한다.하지만 편집은 어떨까?

나는 VUEJS, VUEX, 자바스크립트와 함께 일하고 있어.

내가 하는 일의 예:

<b-button type="submit" @click.prevent="submit()">SAVE</b-button>

methods: {      
  submit() {
    this.$v.edit_category.$touch();
    if(this.$v.edit_category.$error) return
    this.editCategory()
  },
  editCategory() {
    const category = {
      value: this.edit_category.value,
      text: this.edit_category.text,
      category_active: this.edit_category.category_active,
    }        
    
    this.$store.commit('saveCategory', category)
  },
},

store.js:

actions: {
addCategory({ commit }, payload) {
  console.log(payload)
  commit('addCategory', payload) 
},
saveCategory({ commit }, payload) {
  console.log(payload)
  commit('saveCategory', payload) 
},
 deleteCategory({ commit }, payload) {
  console.log(payload)
  commit('deleteCategory', payload) 
}


mutations: {
addCategory(state, category) {   
  state.categories.push(category)      
},
saveCategory(state, payload) {
  state.categories.push(payload)
},
deleteCategory(state, category) {
  var index = state.categories.findIndex(c => c.value === category.value)
  state.categories.splice(index, 1)
},

사용:

import Vue from 'vue';
// ...

editCategory(state, category) {
  var index = state.categories.findIndex(c => c.value === category.value);
  Vue.set(state.categories, index, category);  // ✅ Vue.set
},

이것은 우리가 보는 문서를 읽기 때문에 필요하다.

Vue는 어레이에 대한 다음 변경 사항을 감지할 수 없음:

예를 들어, 인덱스로 항목을 직접 설정할 때vm.items[indexOfItem] = newValue

참조URL: https://stackoverflow.com/questions/66549160/how-to-update-a-state-array-in-vuex

반응형