programing

Vuex 저장소에 올바르게 추가할 수 없음

prostudy 2022. 4. 19. 19:06
반응형

Vuex 저장소에 올바르게 추가할 수 없음

나는 이 Vuex 2 가게를 가지고 있다.

const datastore = new Vuex.Store({
  state: {          
    socketcluster: {
      connection: false,
      channels: []
    },
    selected_offers: []
  },
  mutations: {
    addOffer: function(offer) {
      datastore.state.selected_offers.push(offer) // first problem: cannot just use state.offers as it throws an undefined
    }
  },
  getters: {
    getOffers: function(){
      return datastore.state.selected_offers; 
    }
  }
});

Vue 2 구성 요소 내에서 다음 작업을 수행하십시오.

  methods: {
    clicked: function(){
      console.log("Toggle Offer");
      if ( datastore.getters.getOffers.filter(function(o){ o.id == this.offer.id } ).length == 0 ) {
        // add it
        datastore.commit('addOffer', this.offer)
      } else {
        // TODO remove it
      }
    }
}

어떻게 되는가 하면, 메소드를 트리거하면 다음과 같이 가게가 바뀐다.

여기에 이미지 설명을 입력하십시오.

내가 뭘 잘못하고 있는 거지?

이것은 vuex 패턴으로 작업하는 간단한 방법이다. 큰 애플리케이션에서는 "나처럼" 구성 요소에서 직접 상태를 변경하지 말고 작업을 사용하십시오. 그렇다면 vuex에 대해 더 읽어보십시오.

const store = new Vuex.Store({
  state: {          
    socketcluster: {
      connection: false,
      channels: []
    },
    selected_offers: [ "offer1", "offer2"]
  },
  mutations: {
    addOffer: function( state, offer ) {
      state.selected_offers.push(offer);
    }
  },
  getters: {
    getOffers: function( state ){
      return state.selected_offers; 
    }
  }
});

new Vue({ 
    store,
    data: function() {
      return {
          offer: "offer3"
      }
    },
    methods: {
      clicked: function() {
        if ( this.offers.length === 2 ) {
            this.$store.commit('addOffer', this.offer)
        } else {
          // TODO remove it
        }
      }
    },
    computed: {
        offers: function() {
            return this.$store.getters.getOffers;
        }
    }
}).$mount( "#app" );
<script src="https://vuejs.org/js/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.js"></script>


<div id="app">
    <div v-for="offer in offers" > {{offer}}</div>
    <button @click="clicked"> clicked </button>
</div>

돌연변이에 전달된 첫 번째 매개 변수는state반대하다그래서, 당신은 모든 것을 밀어붙이고 있는 겁니다.state에 반대하다selected_offers대열을 갖추다

당신의 돌연변이 방법은 다음과 같아야 한다.

mutations: {
  addOffer: function(state, offer) {
    state.selected_offers.push(offer)
  }
},

vuex 돌연변이에 대한 설명서는 다음과 같다.

참조URL: https://stackoverflow.com/questions/43853843/cannot-add-to-vuex-store-correctly

반응형