我是Vue.js的新手,在Vuex模块和Axios方面遇到了一个问题。我有一个 "post "组件,它从路由器中检索一个slug,并用Axios获取数据,然后用Vuex Getters检索。
我能够成功地检索数据,但我仍然在DevTools上看到这个错误。"TypeError.Cannot read property 'name' of undefined 无法读取未定义的'name'属性"
由于这个错误,我无法通过 this.post.name
到Vue-Meta。
编码
Post.vue
computed: {
...mapGetters(["post"]),
},
mounted() {
const slug = this.$route.params.slug;
this.fetchPost({ slug: slug });
},
methods: {
...mapActions(["fetchPost"]),
商店模块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
作为一个param,但并没有使用它。相反,它返回一个变量(post
),但在该上下文中还没有定义。它将总是返回 undefined
,无论当前的价值是多少 state.post
. 而且,正如你已经知道的,JavaScript不能访问属性 'name'
的 undefined
.
要获得当前的 state.post
,使用。
const getters = {
post: state => state.post
}
或者
const getters = {
post: (state) => { return state.post; }
}
...如果你喜欢用括号的话。
另外,出于原则,我建议用一个空对象来初始化你的帖子。{}
而不是一个空数组 []
.尽可能少地改变变量类型是一个非常好的编码习惯,从长远来看,提供了巨大的好处。
编辑 (在[MCVE]之后)
你有个更大的问题:从你的axios插件导入时,返回的是 undefined
. 所以你不能叫 get
上。因为你把那个电话包装成了 try/catch
块,你不会看到错误,但端点从未被调用。我不知道你从哪里学来的插件语法,但这显然不是导出axios。将导入替换为 import axios from 'axios'
工作如期进行。
另一个建议是 namespace
您的存储模块。当你有一个以上的模块,并且你想在一个特定的模块上特别引用一个特定的突变动作时,这就会变得很有用。您需要稍微修改 mapActions
和 mapGetters
在这一点上。
看到它的工作 此处.