从vue.js中的存储中获取的计算属性的Setter
我想做两个复选框,从从vue.js中的存储中获取的计算属性的Setter,vue.js,vuex,Vue.js,Vuex,我想做两个复选框,从store.js获取值,并通过表单将它们发送到后端: 通知我 给我发电子邮件 我将这些值作为计算属性获取: 计算:{ 基本URL(){ 返回此。$store.state.BASE\u URL; }, 通知(){ 返回此。$store.state.notification; }, 电子邮件(){ 返回此。$store.state.email; } } 问题是,选中复选框不会更改存储中的值,此外,我在控制台中收到以下警告: vue.esm.js?65d7:479 [Vue
store.js
获取值,并通过表单将它们发送到后端:
通知我
给我发电子邮件
我将这些值作为计算属性获取:
计算:{
基本URL(){
返回此。$store.state.BASE\u URL;
},
通知(){
返回此。$store.state.notification;
},
电子邮件(){
返回此。$store.state.email;
}
}
问题是,选中复选框不会更改存储中的值,此外,我在控制台中收到以下警告:
vue.esm.js?65d7:479 [Vue warn]: Computed property "notification" was assigned to but it has no setter.
我知道可以在computed属性中定义setter,就像在vue.js文档中一样,但我不知道在有多个值要设置时如何定义setter,就像在我的特殊情况下一样
因此,感谢您的帮助解决此问题。要更改Vuex状态,您需要进行变异 如果您有用于更改
通知
状态的设置通知
,您可以在组件中按如下方式配置属性:
computed: {
notification: {
get() { return this.$store.state.notification; },
set(value) { this.$store.commit('setNotification', value); },
},
},
computed: {
...mapStateTwoWay({
notifications: 'setNotifications',
email: 'setEmail',
}),
// Namespaced
...mapStateTwoWay('namespace', {
notifications: 'setNotifications',
email: 'setEmail',
}),
}
现在,您可以像往常一样使用v-model=“notification”
绑定到它
有关更多信息,请参阅文档中的
因为这是我在项目中经常做的事情,所以我编写了一个helper函数来生成计算属性:
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: {
notification: {
get() { return this.$store.state.notification; },
set(value) { this.$store.commit('setNotification', value); },
},
},
computed: {
...mapStateTwoWay({
notifications: 'setNotifications',
email: 'setEmail',
}),
// Namespaced
...mapStateTwoWay('namespace', {
notifications: 'setNotifications',
email: 'setEmail',
}),
}
这对嵌套对象状态有效吗?如
user.info.shippingAddress.street
?对于嵌套的namspacing,重写namspacing getter如下:第1行:let stateNs=this.$store.state代码>第2行:args[0].split('/').forEach(nsComp=>(stateNs=stateNs[nsComp])代码>第3行:返回状态[prop]