【问题标题】:Accessing properties of a prop object that is asynchronously defined访问异步定义的 prop 对象的属性
【发布时间】: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


【解决方案1】:

在初始渲染中,您的数据尚不可用,因此您必须在出现错误的任何地方添加条件渲染:

<template>
  <section class="container">
    <h2 class="title" v-if="config">
      {{ config.section_header }}
    </h2>
    <template v-if="config && config.section_buttons">
      <custom-button
        v-for="(button, i) in config.section_buttons"
        :key="i"
        v-bind="button"
      />
    </template> 
 </section>
</template>

【讨论】:

  • 谢谢!但仍然出现相同的错误:Cannot read property 'section_buttons' of null{{ config.section_header }} 也出现类似错误
  • 是的,你应该这样做&lt;template v-if="config &amp;&amp; config.section_buttons"&gt;请检查编辑后的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 2012-05-04
相关资源
最近更新 更多