programing

Vuex - 동작에만 돌연변이 노출

copyandpastes 2022. 8. 23. 22:50
반응형

Vuex - 동작에만 돌연변이 노출

Vuex를 사용하여 검색 로직과 같은 클라이언트-서버 통신 상태를 저장하려고 합니다.

// status is either synching|synched|error
state: { query:"", result:[], status:"synching" } 

검색 액션을 실행합니다.동작은 돌연변이를 통해서만 상태를 수정할 수 있습니다.

function search(context, query) {
    context.commit("query", query);
    context.commit("status", "synching");

    // some asynch logic here
    ...
        context.commit("result", result);
        context.commit("status", "synched");
    ...
}

그러나 이제 돌연변이는 내 성분에도 노출되어 내 상태를 일관되게 만들 수 있습니다.컴포넌트로부터 돌연변이를 숨길 수 있습니까?

액션은 상태를 직접 변경할 수 있습니다.나중에 잘못 사용할 수 있는 다른 것을 만들 필요가 없습니다.행동을 직접 사용하세요.

var store = new Vuex({
  state: {
    something: ''
  },
  actions: {
    async updateSomethingAsynchronnousWay ({state}, payload) {
      var response = await axios.get(payload.src)
      state.something = response.data.anyKey
    }
  }
})

new Vue({
  store
  el: '#app',
  created () {
    this.$store.dispatch({
      type: 'updateSomethingAsynchronnousWay,
      src: 'https//your.rest.api/something'
    })
  }
})

언급URL : https://stackoverflow.com/questions/47052456/vuex-expose-mutations-only-to-actions

반응형