我想做两个复选框,从store.js中获取值,并通过表单将其发送到后端:

<label>Notify me 
    <input type="checkbox" v-model="notification" value="notification" />       
</label>

<label>Email me 
    <input type="checkbox" v-model="email" value="email" />     
</label>

我将这些值作为计算(computed)属性:

computed: {
  BASE_URL () {
    return this.$store.state.BASE_URL;  
  }, 
  notification () {
    return this.$store.state.notification; 
  },

  email () {
    return this.$store.state.email; 
  }
}

问题是,选中复选框不会更改存储中的值,此外,我在控制台中收到以下警告:

vue.esm.js?65d7:479 [Vue warn]: Computed property "notification" was assigned to but it has no setter.

我知道可以在计算(computed)属性中定义setter,在vue中定义为described.js文档,但我不知道当有多个值要设置时如何设置,比如在我的特殊情况下.

谢谢你帮我解决这个问题.

推荐答案

要改变Vuex状态,需要进行变异.

如果您有一个用于更改notification状态的变量setNotification,您可以在组件中如下配置属性:

computed: {
    notification: {
        get() { return this.$store.state.notification; },
        set(value) { this.$store.commit('setNotification', value); },
    },
},

现在你可以像往常一样用v-model="notification"绑定到它.

更多信息请参见文档中的Form Handling.


因为这是我在项目中经常做的事情,所以我编写了一个helper函数来生成计算(computed)属性:

function mapStateTwoWay(...args) {
    const result = {};

    if (args.length === 1) {
        for (const prop of Object.keys(args[0])) {
            result[prop] = {
                get() { return this.$store.state[prop]; },
                set(value) { this.$store.commit(args[0][prop], value); },
            };
        }
    } else {
        for (const prop of Object.keys(args[1])) {
            result[prop] = {
                get() { return this.$store.state[args[0]][prop]; },
                set(value) { this.$store.commit(args[0] + '/' + args[1][prop], value); },
            };
        }
    }

    return result;
}

这样使用:

computed: {
    ...mapStateTwoWay({
        notifications: 'setNotifications',
        email: 'setEmail',
    }),

    // Namespaced
    ...mapStateTwoWay('namespace', {
        notifications: 'setNotifications',
        email: 'setEmail',
    }),
}

Vue.js相关问答推荐

虚拟DOM在Vue中姗姗来迟

如何使用composition api v-model Select 框获取其他JSON 值?

如何使用 vueJS 上的 ref( ) 函数创建二维数组定义?

视图中的 vue 样式不适用于 html

Vue.js 3 运行时挂载组件实例

如何解决 importers[path] is not a function for clean Vue 3/Vite/Storybook installation

为什么我在 Vue npm run serve 的 localhost 中得到无法获取

如何使用 Vue 命名插槽呈现静态内容列表?

如何使用 v-on:change 将输入文本传递给我的 vue 方法?

使用 vee-validate 在 vue js 中进行验证有错误

查看 cli3 启用 CORS

全局方法和实例方法有什么区别?

在 v-for 的情况下如何从 v-model 输入更新 Vuex 存储

vuex: unknown getter: user

vue-router的router-link实际刷新?

删除一行后刷新 Bootstrap-Vue 表

使用 refs 聚焦元素目标

Vue Js如何在单个文件模板中使用mixins?

v-bind:class 的 Vue.js 计算(computed)属性

vue-cli@3 没有可用于依赖类型的模块工厂:CssDependency