这就是我请求获取组件中数据的方式:
computed: {
...mapGetters([
'showNews'
]),
},
mounted() {
this.$store.dispatch('newsById', this.id /* в компонент передается props id */);
}
newsById
在action
store/index.js中看起来像这样:
newsById({ commit }, id) {
axios.get(`/news/${id}`, apiConfig)
.then(response => {
console.log(response);
commit('newsByIdMutation', response);
})
}
newsByIdMutation
在mutations
store/index.js中看起来像这样:
newsByIdMutation(state, newsById) {
state.showNews = newsById.data;
}
{{ showNews.title }}
在组件的标记中,我试图以这种方式访问该对象{{ showNews.text }}
。但我得到一个错误:Uncaught (in promise) TypeError: Cannot read property 'title_img' of undefined
。我如何在我得到的对象中获取这些属性?
Vue
依赖数据。渲染始终是同步的。axios
该组件在尝试呈现模板之前不会等待任何调用完成。这是一种典型情况 - 与问题中的错误类似的错误是如何发生的:
尽管在此示例中
title
它已成功构建到模板中(由于反应性),但在渲染阶段我们收到一个错误,通知我们模板使用未定义的数据(因为在渲染阶段它也vue
接收obj
到undefined
因为找不到在属性模板中声明的title
- 引发错误)。为了避免这种错误,您应该使用指令
v-if
(条件渲染)(在组件的模板中,或者在组件本身,在父模板中)来处理组件已经渲染但还没有数据可用的情况。让我们重写示例以消除错误: