带有 setter 的 mapState [英] mapState with setter
问题描述
我想通过 mapState
分配 setter 方法.我目前使用一种解决方法,将我感兴趣的变量 (todo
) 命名为临时名称 (storetodo
),然后在另一个计算变量 中引用它>待办事项代码>.
I would like to assign setter methods via mapState
. I currently use a workaround where I name the variable that I am interested in (todo
) as a temporary name (storetodo
) and then refer to it in another computed variable todo
.
methods: {
...mapMutations([
'clearTodo',
'updateTodo'
])
},
computed: {
...mapState({
storetodo: state => state.todos.todo
}),
todo: {
get () { return this.storetodo},
set (value) { this.updateTodo(value) }
}
}
我想跳过额外的步骤并直接在 mapState
中定义 getter、setter.
I would like to skip the extra step and define the getter, setter directly within mapState
.
我为什么要这样做?
通常的方法是使用 mapMutations
/mapActions
&mapState
/mapGetters
没有我上面说明的计算得到/设置组合并直接在 HTML 中引用突变:
The normal approach would be use mapMutations
/mapActions
& mapState
/mapGetters
without the computed get/set combination that I have illustrated above and to reference the mutation directly in the HTML:
<input v-model='todo' v-on:keyup.stop='updateTodo($event.target.value)' />
getter/setter 版本允许我简单地写:
The getter/setter version allows me to simply write:
<input v-model='todo' />
推荐答案
你不能在 mapState
您可以尝试的是直接返回 get()
中的状态并从计算属性中删除 mapState
what you can try is directly return the state in your get()
and remove mapState
from the computed property
computed: {
todo: {
get () { return this.$store.state.todos.todo},
set (value) { this.updateTodo(value) }
}
}
这是一个相关但不相同的 JsFiddle 示例
Here is a related but not same JsFiddle example
这篇关于带有 setter 的 mapState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!