Programing

확인란을 Vuex 저장소에 바인딩하는 방법?

c10106 2022. 4. 19. 21:00
반응형

확인란을 Vuex 저장소에 바인딩하는 방법?

나는 몇 개의 확인란이 들어 있는 구성요소를 가지고 있다.내 Vue 응용 프로그램의 다른 구성 요소에서 어떤 확인란에 액세스할 수 있어야 하지만, 이 확인란들을 내 Vuex 저장소에 어떻게 적절하게 연결해야 하는지를 아무리 생각해도 찾을 수 없다.

구성 요소 내의 확인란을 Vuex 저장소에 연결하여 해당 확인란이 v-model을 통해 구성 요소 데이터에 연결된 것처럼 작동하는 올바른 방법은?

여기 내가 하고자 하는 일의 출발점이 있다(아주 기본적인 의미에서)

https://jsfiddle.net/9fpuctnL/

<div id="colour-selection">
  <colour-checkboxes></colour-checkboxes>
</div>

<template id="colour-checkboxes-template">
  <div class="colours">
    <label>
      <input type="checkbox" value="green" v-model="colours"> Green
    </label>
    <label>
      <input type="checkbox" value="red" v-model="colours"> Red
    </label>
    <label>
      <input type="checkbox" value="blue" v-model="colours"> Blue
    </label>
    <label>
      <input type="checkbox" value="purple" v-model="colours"> Purple
    </label>
    
    <chosen-colours></chosen-colours>    
  </div>
</template>

<template id="chosen-colours-template">
  <div class="selected-colours">
      {{ colours }}
    </div>
</template>

const store = new Vuex.Store({
  state: {
    colours: []
  }
});

Vue.component('colour-checkboxes', {
  template: "#colour-checkboxes-template",
  data: function() {
    return {
      colours: []
    }
  }
});

Vue.component('chosen-colours', {
    template: "#chosen-colours-template",
  computed: {
    colours() {
        return store.state.colours
    }
  }
});

const KeepTalkingSolver = new Vue({
  el: "#colour-selection"
});

목표는 색상 체크 박스 구성 요소에서 선택한 색상을 Vuex 스토어를 통해 선택한 색상 구성 요소로 출력하는 것이다.

계산된 속성을 계산된 속성에서 vuex gettersetter로 사용할 수 있으며, 이를 위해 해당 상태 속성에 대한 돌연변이를 호출할 것이다.

다음의 양방향 계산 속성을 통해 이 예제를 볼 수 있다.

<input v-model="message">
// ...
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}

나는 실제로 확인란을 사용하는 대답을 제공하고 싶었다.

여기에 설명되어 있는 가능한 해결책이 하나 있다: Vuex 동적 확인란 바인딩

그리고 다음과 같은 간단한 해결책을 얻을 수 있다.

<div v-for="tenant in tenants" 
     v-bind:key="tenant.id" 
     class="form-group form-check">

<input type="checkbox" 
     class="form-check-input" 
     v-bind:id="tenant.id" 
     v-bind:value="tenant.name" 
     @change="updateSelectedTenants">

여기서 열쇠는 온 체인지(on-change)를 이용한 메서드를 호출하는 것으로, 변경에 필요한 모든 세부사항과 함께 이벤트를 메서드에 전달한다.

@change 함수:

updateSelectedTenants(e) {
  console.log('e', e.target)
  console.log('e', e.target.value)
  this.$store.dispatch('updateSelectedTenants', e.target)
}

여기서 나는 값을 원한다. 이 경우에는 세입자 이름이 될 것이다. 그러나 대상에 대한 추가 검사 또한 'id'를 제공하며, 확인란이 '체크'되었는지 아니면 체크되지 않았는지 여부를 알려준다.

매장 내에서는 '선택한' 사람들을 조종할 수 있다.테넌트 어레이:

updateSelectedTenants (context, tenant) {
  if(tenant.checked) {
    // Tenant checked, so we want to add this tenant to our list of 'selectedTenants'
    context.commit('addSelectedTenant', { id: tenant.id, name: tenant.value })
  } else {
    // otherwise, remove the tenant from our list
    context.commit('removeSelectedTenant', tenant.id)
  }
}

여기 실제 돌연변이들이 있다.

addSelectedTenant (state, tenant) {
  this.state.selectedTenants.push(tenant)
},
removeSelectedTenant (state, id) {
  this.state.selectedTenants = this.state.selectedTenants.filter(tenant => {
    return tenant.id != id
  })

Vuejs 문서들은 훌륭하지만, 때때로 그들은 실제 세계의 예들로 약간 조명될 수 있다.get(), set()...로 계산된 값을 사용하여 위와 같은 것을 달성하는 것은 불가능하다고 생각하지만, 할 수 있는 해결책을 보고 싶다.

좋아, 나는 내 해결책을 보여주려는 도전을 받아왔다.여기 jsfiddle에 있다.

html:

<div id="app">
  <label v-for="brother in ['Harpo','Groucho','Beppo']">
    <input type='checkbox' v-model='theBrothers' v-bind:value='brother' />
      {{ brother }}
  </label>
  <div>
  You have checked: {{ theBrothers }}
  </div>
</div> 

그리고 js는 다음과 같다.

const store = new Vuex.Store({
  state: {
    theBrothers: []
  },
})

new Vue({
  el: "#app",
  store: store,
  computed: {
    theBrothers: {
      set(val){this.$store.state.theBrothers = val},
      get(){ return this.$store.state.theBrothers }
    }
 },
}) 

2021년 - 쉽고 읽기 쉬우며 Vue/Vuex의 힘을 활용하는 것...

간단한 문제에는 복잡한 답이 많다.아래 코드 조각을 실행하여 작동하는지 확인하십시오.

장황한 줄거리만 가지고 가면 된다(주(州)의 한 조각만 가져가면 된다.names아래, 돌연변이 생성(setNames아래)를 설정하여 바인딩하십시오.v-model완전히computed(selectedNames아래) getter와 setter가 있는 getter는 상태 부분을 얻는다.names그리고 세터는 돌연변이를 부른다.setNames.

내 생각에 이것은 Vue/Vuex의 자연스러운 패턴을 따르고 일반적으로 확인란이 어떻게 구현되는지를 따르기 때문에 이 문제에 대한 가장 깨끗한 해결책이다.

여기서의 다른 답변은 돌연변이 없이 상태를 직접 변이하려고 하는 반면, 다른 답변은 다음 명령어를 사용하지 않는다.v-model사전 선택된 값을 갖는 문제와 더 많은 코드를 필요로 하며 마지막으로 승인된 답변은 HTML 템플릿 코드를 구현하는 방법조차 보여주지 않는다.

다음은 이러한 모든 문제를 해결하는 작업 솔루션이다.

const store = new Vuex.Store({
  state: {
    names: ['Max'],
  },
  mutations: {
    setNames(state, names) {
      state.names = names;
    }
  }
});

new Vue({
  el: '#app',
  store,
  computed: {
    selectedNames: {
      get: function() {
        return this.$store.state.names;
      },
      set: function(val) {
      console.log(val);
        this.$store.commit('setNames', val);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vuex@3.6.2/dist/vuex.js"></script>

<div id="app">
  <div>
    <input type="checkbox" v-model="selectedNames" :value="'John'" id="checkbox-1" />
    <label for="checkbox-1">Click me to add my value to the state</label>

    <br />

    <input type="checkbox" v-model="selectedNames" :value="'Max'" id="checkbox-2" />
    <label for="checkbox-2">I am preselected since my value already exists in the state <code>names</code> array</label>

    <div>State: <strong>{{ names }}</strong></div>
  </div>
</div>

사용하다@change필요에 따라 Vuex를 업데이트하려면:

HTML:

<input
  v-for='item in items'
  @change='update_checkboxes'
  v-model='selected_checkboxes'
  :value='item.id'
  type='checkbox
/>
<label>{{item.name}}</label>

JS:

data: function(){ 
  return {
    selected_checkboxes: [] // or set initial state from Vuex with a prop passed in
  }
},
methods: {
  update_checkboxes: function(){
    this.$store.commit('update_checkboxes', this.selected_checkboxes)
  }
}

@Saurabh의 솔루션을 기반으로 - vuex 상태에 직접 액세스하기보다는 작업게이터를 사용하는 것이 중요하다 - 이것은 애플리케이션 전체에 걸쳐 일관성을 보장할 것이다.

<p>Mega test: <input type="checkbox" v-model="mega" /></p>
computed: {
  mega: {
    get () {
      return this.$store.getters.mega
    },
    set (value) {
      this.$store.dispatch('updateMega', value)
    }
  }
}
const store = new Vuex.Store({
  state: {
    mega: false
  },
  getters: {
    mega (state) {
      return state.mega
    }
  },
  mutations: {
    updateMega (state, value) {
      state.mega = value
    }
  },
  actions: {
    updateMega (context, value) {
      context.commit('updateMega', value)
    }
  }
})

데이터에서 색상 = []을(를) 제거하십시오.

참조URL: https://stackoverflow.com/questions/42686388/how-to-bind-checkboxes-to-vuex-store

반응형