我们应该使用v模型修改Vuex存储吗?

Kan*_*now 5 javascript vue.js vuex vuejs2 v-model

您好,我是Vue的初学者,确实有一个困扰我的问题。我想知道我们应该使用v-model指令来修改vuex存储吗?Vuex说我们应该只通过突变来修改vuex存储,但是v-model使一切变得更容易和更短。(我问是因为我找不到明确的答案)

Sim*_*iel 8

上述解决方案也可以通过突变来实现:

<template>
  <input v-model="message">
</template>

<script>
import { mapMutations, mapState } from 'vuex';

export default {
  computed: {
    ...mapState({messageFromStore: 'message'}),
    message: {
      get() {
        return this.messageFromStore;
      },
      set(value) {
        this.updateMessage(value);
      }
    }
  },
  methods: {
    ...mapMutations('updateMessage')
  }
};
</script>
Run Code Online (Sandbox Code Playgroud)


cee*_*yoz 7

https://vuex.vuejs.org/guide/forms.html

在严格模式下使用Vuex时,在v-model属于Vuex的状态下使用可能会有些棘手。

处理它的“ Vuex方法”是绑定<input>的值,并在输入或更改事件上调用操作。

确保在该页面上查看简单的“双向计算属性”示例:

<input v-model="message">

computed: {
  message: {
    get () {
      return this.$store.state.obj.message
    },
    set (value) {
      this.$store.commit('updateMessage', value)
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的解决方案。我将其修改为使用调度(“SomeAction”)而不是提交。因为使用操作是推荐的方法。 (3认同)

Raj*_*Raj 7

我认为这里的任何答案中都没有提到的另一个不错的选择是使用vuex-map-fields。事实上,库作者已经为库的用处写了一个非常好的解释。根据其 GitHub 页面,要使用该库,您可以执行以下操作:

在你的 Vuex Store 中,你可以有一个类似这样的片段:

import Vue from 'vue';
import Vuex from 'vuex';

import { getField, updateField } from 'vuex-map-fields';

Vue.use(Vuex);

export default new Vuex.Store({
  // ...
  modules: {
    fooModule: {
      namespaced: true,
      state: {
        foo: '',
      },
      getters: {
        getField,
      },
      mutations: {
        updateField,
      },
    },
  },
});
Run Code Online (Sandbox Code Playgroud)

在你的组件代码中,你可以有这样的东西:

<template>
  <div id="app">
    <input v-model="foo">
  </div>
</template>

<script>
import { mapFields } from 'vuex-map-fields';

export default {
  computed: {
    // `fooModule` is the name of the Vuex module.
    ...mapFields('fooModule', ['foo']),
  },
};
</script>
Run Code Online (Sandbox Code Playgroud)

库的 GitHub 存储库中显示了各种用例的其他示例,我在此答案的第一句中链接到了该存储库。