0x0*_*0x0 2 javascript vue.js vuex vuex-modules
我是 Vue.js 的新手,遇到了 Vuex 模块和 Axios 的问题。我有一个“post”组件,它从路由器中检索 slug 并使用 Axios 获取数据,然后使用 Vuex Getters 检索数据。
我能够成功检索数据,但随后我仍然在我的 DevTools 上看到此错误,“TypeError:无法读取未定义的属性‘名称’”
由于这个错误,我无法传递this.post.name给 Vue-Meta。
代码
后.vue
computed: {
...mapGetters(["post"]),
},
mounted() {
const slug = this.$route.params.slug;
this.fetchPost({ slug: slug });
},
methods: {
...mapActions(["fetchPost"]),
Run Code Online (Sandbox Code Playgroud)
/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,
};
Run Code Online (Sandbox Code Playgroud)
你的 getter 是完全错误的:状态 getter 应该是一个函数,它将整个state作为参数并从中检索你感兴趣的任何东西。你的版本...
const getters = {
post: (state) => {
return post;
}
};
Run Code Online (Sandbox Code Playgroud)
...state作为参数接受但不使用它。相反,它返回一个post尚未在该上下文中定义的变量 ( )。无论 的当前值如何,都
将始终返回。
而且,正如你已经知道,JavaScript不能访问属性的。undefinedstate.post'name'undefined
要获取 的当前值state.post,请使用:
const getters = {
post: state => state.post
}
Run Code Online (Sandbox Code Playgroud)
或者
const getters = {
post: (state) => { return state.post; }
}
Run Code Online (Sandbox Code Playgroud)
...如果你喜欢括号。
另外,出于原则,我建议使用空对象{}而不是空数组来初始化您的帖子[]。尽可能少地更改变量类型是一种非常好的编码习惯,从长远来看会带来巨大的好处。
编辑(在 [mcve] 之后)
你有一个更大的问题:从你的 axios 插件导入返回undefined. 所以你不能调用get它。因为您将该调用包装到一个try/catch块中,所以您看不到错误,但永远不会调用端点。
我不知道您从哪里选择了该插件语法,但它显然没有导出 axios。用import axios from 'axios'预期的工作替换导入。
另一个建议是namespace您的商店模块。当您拥有多个模块并且您希望在特定模块上专门引用特定的更改/操作时,这将变得很有用。你需要稍微改变mapActions,并mapGetters在这一点上。
看到它在这里工作。
| 归档时间: |
|
| 查看次数: |
285 次 |
| 最近记录: |