【问题标题】:Nuxt Vuex State and Getters Has Data But Grayed OutNuxt Vuex State 和 Getters 有数据但显示为灰色
【发布时间】: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"]),但这可能不是问题

标签: vue.js vuejs2 vuex


【解决方案1】:

编辑:想通了!

我正在运行 Nuxt,在修改了文档后,我意识到该框架已经构建了许多在使用 vanilla Vuex 时需要创建的对象。下面是设置商店的正确方法!

import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);

export const state = () => ({
  tiers: [
    {
      id: 1,
      name: "Director Subscription",
      price: 25
    },
    {
      id: 2,
      name: "Regular Subscription",
      price: 10
    },
    {
      id: 3,
      name: "Regular+ Subscription",
      price: 15
    }
  ],
  StoreCart: []
});

export const mutations = {
  ADD_Item(state, id) {
    state.StoreCart.push(id);
  },
 
  REMOVE_Item(state, index) {
    state.StoreCart.splice(index, 1);
  }
};
export const actions = {
  addItem(context, id) {
    context.commit("ADD_Item", id);
  },
  removeItem(context, index) {
    context.commit("REMOVE_Item", index);
  }
};


export const getters = {
  isAuthenticated(state) {
    return state.auth.loggedIn;
  },
  loggedInUser(state) {
    return state.auth.user;
  },
  tiers: state => state.tiers,
  StoreCart: state => state.StoreCart
};

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 2023-02-09
    • 2013-02-21
    • 1970-01-01
    • 2020-11-26
    • 2021-01-06
    • 2011-12-03
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多