如何将复选框绑定到Vuex存储?

2024-04-20

我有一个包含一些复选框的组件。我需要能够访问从 Vue 应用程序中的其他组件检查了哪些复选框,但我无法弄清楚(也无法在网上找到)如何将复选框正确连接到我的 Vuex 商店。

将组件内的复选框连接到 Vuex 存储的正确方法是什么,以便它们的行为就像复选框通过 v-model 连接到组件数据一样?

这是我想做的事情的起点(在非常非常基本的意义上)

https://jsfiddle.net/9fpuctnL/ 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 存储,将 color-checkboxes 组件中选择的颜色输出到 selected-colours 组件中。


您可以使用计算属性 https://v2.vuejs.org/v2/guide/computed.html吸气剂为vuex 获取器 https://vuex.vuejs.org/en/getters.html and setter https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter在计算属性中,它将调用mutation https://vuex.vuejs.org/en/mutations.html让该国有财产来做这件事。

你可以看一个例子here https://vuex.vuejs.org/en/forms.html具有双向计算属性:

<input v-model="message">
// ...
computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将复选框绑定到Vuex存储? 的相关文章

随机推荐