使用setter的mapState

vue.js Vue.js

阿飞Pro

2020-03-16

我想通过指定分配器方法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) }
    }
}

我想跳过多余的步骤,直接在中定义getter,setter mapState

我为什么要这样做?

正常的方法是使用mapMutations/ mapActionsmapState/ / mapGetters 而不使用上面已经说明的计算的get / set组合,并直接在HTML中引用该突变:

<input v-model='todo' v-on:keyup.stop='updateTodo($event.target.value)' />

getter / setter版本允许我简单地编写:

<input v-model='todo' />

第1807篇《使用setter的mapState》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
逆天小胖Mandy 2020.03.16

您不能在其中使用getter / setter格式 mapState

您可以尝试直接返回状态get()mapState从计算的属性中删除

computed: {
    todo: {
        get () { return this.$store.state.todos.todo},
        set (value) { this.updateTodo(value) }
    }
} 

这是一个相关但不相同的JsFiddle示例

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android