我想制作两个从中获取价值的复选框,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>
Run Code Online (Sandbox Code Playgroud)
我将值作为计算属性获取:
computed: {
BASE_URL () {
return this.$store.state.BASE_URL;
},
notification () {
return this.$store.state.notification;
},
email () {
return this.$store.state.email;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是检查复选框不会更改商店中的值,除此之外,我在控制台中收到此警告,如:
vue.esm.js?65d7:479 [Vue warn]: Computed property "notification" was assigned to but it has no setter.
Run Code Online (Sandbox Code Playgroud)
我知道,一个可以在计算财产定义setter方法,如描述在vue.js文档,但我不知道该怎么做,当有多个值来设置,就像在我的具体情况.
非常感谢您的帮助来解决这个问题.
Dec*_*oon 16
要更改Vuex状态,您需要一个变异.
如果您有setNotification更改notification状态的变异,则可以在组件中配置属性,如下所示:
computed: {
notification: {
get() { return this.$store.state.notification; },
set(value) { this.$store.commit('setNotification', value); },
},
},
Run Code Online (Sandbox Code Playgroud)
您现在可以v-model="notification"正常绑定它.
有关详细信息,请参阅文档中的表单处理.
因为这是我在项目中经常做的事情,所以我编写了一个生成计算属性的辅助函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
computed: {
...mapStateTwoWay({
notifications: 'setNotifications',
email: 'setEmail',
}),
// Namespaced
...mapStateTwoWay('namespace', {
notifications: 'setNotifications',
email: 'setEmail',
}),
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7794 次 |
| 最近记录: |