Vue打字稿等待诺言

时间:2020-04-28 12:43:46

标签: javascript typescript vue.js asynchronous axios

我试图显示我从Axios请求中获取的数据。我知道,Axios返回了Promise,我需要等待,这就是为什么它在这里不起作用的原因:

get categories(): Array<string> {
  let categories: Array<string> = []
  api.getORMJson().then((response) => {
    categories = response.data.nodes[0].nodes
    // Correct output
    console.log(response.data.nodes[0].nodes)
  })
  return categories
}

我已经尝试过Promise的方法,但是那也不起作用:

get categories(): Promise<Array<string>> {
  return new Promise<Array<string>>((resolve) => {
    api.getORMJson().then((response) => {
      resolve(response.data.nodes[0].nodes)
    })
  })
}

最终,我希望将数据显示在Select中,例如:

<select>
  <option v-for="category in categories" :key="category" :value="category">
    {{ category }}
  </option>
</select>

编辑:我已经使它工作了一次,但是非常肮脏:

@Prop({ default: [], required: true })
public categories!: Array<string>

吸气剂如下:

get allCategories(): Array<string> {
  return this.categories
}

这里的问题是,我直接在Mounted-Function中更改了属性,如下所示:

mounted() {
      api.getORMJson().then((response) => {
        this.categories = response.data.nodes[0].nodes
      })
  }

然后,我可以轻松地遍历所有类别,并且一切正常,但是Vue给了我我当之无愧的错误:“ [Vue警告]:避免直接更改prop,因为只要父组件重新渲染,值就会被覆盖。根据道具的值使用数据或计算属性。道具被突变:“类别””

0 个答案:

没有答案