Vuex Getter 未定义

Vuex Getter Undefined

我是 Vue.js 的新手,遇到 Vuex 模块和 Axios 的问题。我有一个 "post" 组件,它从路由器检索 slug 并使用 Axios 获取数据,然后使用 Vuex Getters 检索数据。

我能够成功检索数据,但我仍然在我的 DevTools 上看到此错误,"TypeError: Cannot read property 'name' of undefined"

由于这个错误,我无法将 this.post.name 传递给 Vue-Meta。

代码

Post.vue

  computed: {
    ...mapGetters(["post"]),
  },

  mounted() {
    const slug = this.$route.params.slug;
    this.fetchPost({ slug: slug });
  },

  methods: {
    ...mapActions(["fetchPost"]),

/store/modules/post.js

const state = {
  post: [],
};

const getters = {
  post: (state) => {
    return post;
  }
};

const actions = {
  async fetchPost({ commit }, arg) {
    try {
      await axios.get("/post/" + arg.slug).then((response) => {
        commit("setPost", response.data);
      });
    } catch (error) {
      console.log(error);
    }
  },
};

const mutations = {
  setPost: (state, post) => (state.post = post),
};

export default {
  state,
  getters,
  actions,
  mutations,
};

你的 getter 是完全错误的:状态 getter 应该是一个函数,它将整个 state 作为参数并从中检索你感兴趣的任何东西它。你的版本...

const getters = {
  post: (state) => {
   return post;
  }
};

...接受 state 作为参数但不使用它。相反,它 return 是一个尚未在该上下文中定义的变量 (post)。
无论 state.post.
的当前值如何,它总是 return undefined 而且,如您所知,JavaScript 无法访问 undefined 的 属性 'name'

要获取 state.post 的当前值,请使用:

const getters = {
  post: state => state.post
}

const getters = {
  post: (state) => { return state.post; }
}

...如果你喜欢括号。

此外,出于原则,我建议使用空对象 {} 而不是空数组 [] 来初始化您的 post。 尽可能少地更改变量类型是一个很好的编码习惯,在长 运行.

中提供巨大的好处

编辑(在 [mcve] 之后)

您有一个更大的问题:从您的 axios 插件导入 returns undefined。所以你不能在上面调用 get 。因为您将该调用包装到 try/catch 块中,所以您看不到错误,但永远不会调用端点。
我不知道你从哪里选择了那个插件语法,但它显然没有导出 axios。用 import axios from 'axios' 替换导入按预期工作。

另一个建议是 namespace 您的商店模块。当您拥有多个模块并且您希望专门引用特定模块上的特定 mutation/action 时,这将变得很有用。届时您需要稍微更改 mapActionsmapGetters

看到它工作 here