【发布时间】:2021-06-09 18:12:06
【问题描述】:
我的子组件收到一个名为 config 的道具,它是我在模板中显示其属性或作为道具传递给其他组件的对象:
<template>
<section class="container">
<h2 class="title">
{{ config.section_header }}
</h2>
<custom-button
v-for="(button, i) in config.section_buttons"
:key="i"
v-bind="button"
/>
</section>
</template>
父视图组件本身从存储中获取config 对象。
在我的父视图组件中:
created () {
this.initializeStore()
},
computed: {
...mapState({
config: state => state.template?.section ?? null
})
}
通过Axios 调用异步填充存储:
export const actions = {
initializeStore ({ state, commit }, data) {
this.$axios.get('/path/to/api/endpoint')
.then((res) => {
// state object gets populated
})
}
}
因为 config 属性仅在商店 API 调用解决后才定义,所以我的组件在我试图显示它的一部分的任何地方都会抛出 undefined 错误。例如:
无法读取 null 的属性“section_buttons”
如何解决这个问题?
【问题讨论】:
-
你尝试过使用 promises 或 async/await 吗?
标签: vue.js asynchronous