programing

vuex 스토어에 라디오 버튼을 바인딩하는 방법?

prostudy 2022. 5. 25. 22:18
반응형

vuex 스토어에 라디오 버튼을 바인딩하는 방법?

단방향으로 라디오 버튼 집합의 값을 내 모델에 바인딩하고 변경 시 vuex 저장소를 업데이트하고 싶다.불행하게도 이것은 어디에도 기록되어 있지 않은 것 같다.어떤 도움이라도 감사할 것이다.

문서화된 양방향 바인딩 작업:

<input type="radio" name="info-source" value="1" id="info-source-1" v-model="infoSource">
<label for="info-source-1">TV</label>
<input type="radio" name="info-source" value="2" id="info-source-2" v-model="infoSource">
<label for="info-source-2">Social media</label>

하지만 vuex는 이 경우 불평하기 시작한다.Do not mutate vuex store state outside mutation handlers

경고에 따라 변이 방법 이외의 Vuex 상태 개체의 값은 수정할 수 없다.

다음과 같은 계산된 속성을 만들 수 있다.get/setVuex 저장소에 있는 관련 데이터의 상태를 참조/업데이트하는 방법.

여기 간단한 예가 있다.

const store = new Vuex.Store({
  state: {
    gender: 'female',
  },
  mutations: {
    SET_GENDER(state, gender) {
      state.gender = gender;
    }
  }
});

new Vue({
  el: '#app',
  store,
  computed: {
    gender: {
      get() {
        return this.$store.state.gender;
      },
      set(value) {
        this.$store.commit("SET_GENDER", value);
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.3.1/vuex.min.js"></script>
<div id="app">
  <input type="radio" name="gender" value="male" v-model="gender">Male<br>
  <input type="radio" name="gender" value="female" v-model="gender">Female<br>
  <input type="radio" name="gender" value="other" v-model="gender">Other<br>
  Vuex store value: {{ $store.state.gender }}<br>
  Computed property value: {{ gender }}
</div>

블로그 포스트는 나를 올바른 길로 이끌었다.내가 생각해 낸 해결책은 다음과 같다.

<input type="radio" name="info-source" value="1" 
       :checked="infoSource === 1" @change="updateInfoSource(1)">

With theupdateInfoSource스토어에 커밋하는 방법

전체 예를 보려면 다음 게시물을 참조하십시오.vuex 스토어에 라디오 버튼을 바인딩하는 방법?

참조URL: https://stackoverflow.com/questions/45841180/how-to-bind-radio-buttons-to-a-vuex-store

반응형