【发布时间】:2020-10-10 16:35:58
【问题描述】:
我试图用 v-for 从 getter 中提取数据,但我什么也没得到,所以我决定控制台记录“this.$store.getters.tiers”,结果返回未定义。
数据显示在 Vue 浏览器选项卡中,但除非我手动单击该箭头,否则 State 和 Getters 都显示为灰色。空白数据与此有关,还是我在代码中忘记的内容?
感谢您的帮助!
import Vue from "vue";
import { mapGetters } from "vuex";
computed: {
tiers() {
return this.$store.getters.tiers;
},
...mapGetters(["loggedInUser"])
},
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: () => ({
tiers: [
{
id: 1,
name: "Director Subscription",
price: 25
},
{
id: 2,
name: "Regular Subscription",
price: 10
},
{
id: 3,
name: "Regular+ Subscription",
price: 15
}
],
StoreCart: []
}),
getters: {
tiers: state => state.tiers,
StoreCart: state => state.StoreCart
},
mutations: {
ADD_Item(state, id) {
state.StoreCart.push(id);
},
REMOVE_Item(state, index) {
state.StoreCart.splice(index, 1);
}
},
actions: {
addItem(context, id) {
context.commit("ADD_Item", id);
},
removeItem(context, index) {
context.commit("REMOVE_Item", index);
}
},
modules: {}
});
export const getters = {
isAuthenticated(state) {
return state.auth.loggedIn;
},
loggedInUser(state) {
return state.auth.user;
}
};
【问题讨论】:
-
请发布完整的商店和完整的组件。我看到的第一件事是您的 vuex 商店的状态是一个返回对象的函数,但是对于 vue 2 状态的 vuex 3.x 只需要是一个对象。您也可以使用 mapGetters 映射层,而不是像您一样重新创建它 (...mapGetters(["loggedInUser", "tiers"]),但这可能不是问题