我想通过分配setter方法mapState.我目前使用一种解决方法,我将我感兴趣的变量命名为(todo)作为临时名称(storetodo),然后在另一个计算变量中引用它todo.
methods: {
...mapMutations([
'clearTodo',
'updateTodo'
])
},
computed: {
...mapState({
storetodo: state => state.todos.todo
}),
todo: {
get () { return this.storetodo},
set (value) { this.updateTodo(value) }
}
}
Run Code Online (Sandbox Code Playgroud)
我想跳过额外的步骤并直接在其中定义getter,setter mapState.
我为什么要这样做?
正常的方法是使用mapMutations/ mapActions&mapState/ mapGetters
没有我上面说明的计算的get/set组合,并直接在HTML中引用变异:
<input v-model='todo' v-on:keyup.stop='updateTodo($event.target.value)' />
Run Code Online (Sandbox Code Playgroud)
getter/setter版本允许我简单地写:
<input v-model='todo' />
Run Code Online (Sandbox Code Playgroud)
Vam*_*hna 17
你不能在中使用getter/setter格式 mapState
您可以尝试直接返回您的状态get()并mapState从计算属性中删除
computed: {
todo: {
get () { return this.$store.state.todos.todo},
set (value) { this.updateTodo(value) }
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个相关但不完全相同的JsFiddle示例
这是我目前的解决方法。复制自我的个人工作项目
// in some utils/vuex.js file
export const mapSetter = (state, setters = {}) => (
Object.keys(state).reduce((acc, stateName) => {
acc[stateName] = {
get: state[stateName],
};
// check if setter exists
if (setters[stateName]) {
acc[stateName].set = setters[stateName];
}
return acc;
}, {})
);
Run Code Online (Sandbox Code Playgroud)
在你的 component.vue 文件中
import { mapSetter } from 'path/to/utils/vuex.js';
export default {
name: 'ComponentName',
computed: {
...mapSetter(
mapState({
result: ({ ITEMS }) => ITEMS.result,
total: ({ ITEMS }) => ITEMS.total,
current: ({ ITEMS }) => ITEMS.page,
limit: ({ ITEMS }) => ITEMS.limit,
}),
{
limit(payload) {
this.$store.dispatch({ type: TYPES.SET_LIMIT, payload });
},
},
)
},
}
Run Code Online (Sandbox Code Playgroud)
现在您可以使用 v-model 绑定。我
| 归档时间: |
|
| 查看次数: |
9216 次 |
| 最近记录: |