我在vuex中有getter,它从列表中返回项目
const store = new Vuex.Store({
state: { arr: {
1: {name: 'one', attr: true},
2: {name: 'two', attr: false}
},
mutations: {
setArrItemName(state, id, name) {
Vue.set(state.arr, id, name);
}
},
getters: {
arrItemById(state, getters) => (id) => {
const item = state.arr[id];
if(item) return item;
return {
name: 'default', attr: true
};
}
}
})如果我在模板中输出它
{{ $store.state.arr[1]['name'] }}当另一个部件调用时,它可以正常更新
this.$store.commit('setArrItemName', 1, 'new name');但如果模板包含
{{ $store.getters.arrItemById(1).name }}那么它就不会更新
问题:这个getter在不同的地方使用,我不想重复这段代码
<template v-if='$store.state.arr[id]'>
{{ $store.state.arr[id].name }}
</template>
Default
<template v-else>
</template>如果某天“默认”或default对象的任何其他属性发生变化,那么应该在不同的位置更新它。
发布于 2017-05-13 19:33:08
尝试使用计算属性来访问getter。首先,从Vuex导入mapGetters函数:
import {mapGetters} from 'vuex';然后,为所需的getter添加计算属性,如下所示:
computed: {
...mapGetters({
getterName: 'your-getter-name-in-store'
})
} 我们在使用mapGetters帮助器的同时使用了扩展运算符( ... );您可以阅读更多关于为什么使用here的信息。
然后,在您的模板中使用{{ getterName }}。
这还克服了代码重复的问题,因为您不需要在任何地方都使用this.$store.getters。
发布于 2017-07-21 05:19:47
你不能在不纯的getter上得到反应。可以在local上创建计算属性。
资料来源:https://github.com/vuejs/vuex/issues/145#issuecomment-230488443
我做了一些研究,你可以使用内部带有getter的计算函数:
computed: {
arr() {
return this.$store.getters.arrItemById(this.id);
}
},下面是一个jsfiddle示例。
发布于 2017-09-21 08:27:35
我不知道这个打字错误是出现在问题中,还是出现在你的程序中……
来自之上的
const store = new Vuex.Store({
state: { arr: {
1: {name: 'one', attr: true},
2: {name: 'two', attr: false}
},
mutations: {
...应为
const store = new Vuex.Store({
state: { arr: {
1: {name: 'one', attr: true},
2: {name: 'two', attr: false}
} // missing this closing brace on object arr
},
mutations: {
...这可能解释了getter问题。
https://stackoverflow.com/questions/43939024
复制相似问题