Vuex:动态绑定到状态的 属性

Vuex: binding dynamically to a property of the state

我有兴趣制作一个包含多个 div 和一些内容的自定义复选框组件。

我有一家看起来像这样的商店:

var store = Vuex.Store({
  state: {
    lights: true,
    sound: false
  }
});

有什么方法可以创建一个可以接受这些属性之一(lightssound)并对其进行操作的自定义组件?

我现在把所有事情都搞得一团糟。我创建了一个模板:

<div id="app">
  <div class="container">
    <my-switch :name="'lights'"></my-switch>
    <my-switch :name="'sound'"></my-switch>
  </div>
</div>

接下来我使用 this as an example,并尝试将每个复选框绑定到商店中的一个 属性:

Vue.use(Vuex);

var store = Vuex.Store({
  state: {
    lights: true,
    sound: false
  },
  mutations: {
    updateMessage(state, args) {
      state[args.name] = args.value;
    }
  }
});

Vue.component("my-switch", {
  props: ["name"],
  template: '<div>{{ name }} <input type="checkbox" v-model="checked"></div>',
  computed: {
    checked: {
      get() {
        return this.$store.state[this.name];
      },
      set(value) {
        this.$store.commit("updateMessage", { name: this.name, value: value });
      }
    }
  }
});

var v = new Vue({
  el: "#app",
  store: store
});

我在这里破坏了演示: https://codepen.io/EightArmsHQ/pen/dVXeNL?editors=0010

问题是我收到以下错误:

TypeError: Cannot read property 'state' of undefined

您需要通过 new Vuex.Store({...}) 实例化 Vuex 存储(我希望您的代码会抛出错误,但显然不会。)

此外,您不需要 Vue.use(Vuex) 行。

Here's a working Codepen.