javascript - 如何使用 Axios 请求的数据填充 Vue 中的数组

标签 javascript vue.js axios vuetify.js

v-breadcrumbs 显示来自面包屑数组的数据 - 这对于静态数据来说效果很好。

<v-row>
    <!-- Breadcrumbs -->
    <v-col class="d-flex">
        <v-breadcrumbs :items="breadcrumbs"></v-breadcrumbs>
    </v-col>
</v-row>

<v-row>
    <v-col class="d-flex">
        <p class="blue--text title font-weight-medium my-0">{{response.products.title}}</p>
    </v-col>
</v-row>

Axios 发出 get 请求来获取有关产品的各种数据 - 这也可以正常工作。

<script>
export default {
  async asyncData({$axios, params}){
    try{
      let response = await $axios.$get(`/api/products/${params.id}`)
      console.log(responce);

      return{
        responce: responce
      }
    }catch(err){
      console.log(err);
    }
  },
  data: () => ({
    breadcrumbs: [{text: "Category", href: "index"}, {text: "", disabled: true}]
  })
</script>

然后,我想使用从 get 请求返回的数据来传播面包屑数组中的最后一项。

我尝试使用 Promise 在 get 请求完成后插入值,但这样做整个应用程序都会崩溃,并显示“无法读取未定义的属性'产品'”,无论执行什么代码在 promise 中。

let response = await $axios.$get(`/api/products/${params.id}`)
                     .then((result) => {
                       // Some code here
                     })

我意识到我必须在使用 .then() promise 时以某种方式改变“响应”值。这是解决这个问题的最佳方法还是我应该研究 Vue 生命周期 Hook ?

以下是对 get 请求的 API 响应:

{
  success: true,
  products: {
    rating: [],
    _id: '5e3bfd038125ebafba2ff8ce',
    owner: {
      _id: '5e397eed2da03d0817f3f870',
      name: 'Jeff Bezos',
      about: 'Jeff is the owner of this site.',
      photo: '-',
      __v: 0
    },
    category: { _id: '5e397bcc2da03d0817f3f86d', type: 'Books', __v: 0 },
    title: 'The Everything Store',
    description: 'A book about Amazon',
    photo: '-',
    price: 12,
    stockQuantity: 73,
    __v: 0
  }
}

最佳答案

如果你想让一个变量影响你的 DOM,你必须将它声明为 Vue 实例的数据函数中的属性:

data: () => ({
  breadcrumbs: [{text: "Category", href: "index"}, {text: "", disabled: true}],
  response: null
})

然后,为了访问 response 数据属性,您必须使用生命周期 Hook 。例如:

<script>
// import axios if needed

export default {
  data: () => ({
    breadcrumbs: [{text: "Category", href: "index"}, {text: "", disabled: true}]
  }),
  created(){
      // I don't know where params object comes form
      $axios.$get(`/api/products/${params.id}`)
      .then(response => {
        this.response = response;
      })
      .catch(err => {
        console.log(err);
      })
  },

</script>

关于javascript - 如何使用 Axios 请求的数据填充 Vue 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60111020/

相关文章:

Javascript 将 JSON 对象值作为单选按钮或列表的文本

javascript - 如何通过在框覆盖的区域外单击来关闭 jQuery UI 模式对话框?

javascript - Vue.js 和 vue-datepicker : save a picked period in the global state

authentication - NuxtJs - 无法读取未定义的属性 'headers'

async-await - 如何使用 vue + axios 在 get 请求中使用 async/await?

javascript - mobx react 观察者组件在更新后不调用渲染

javascript - Angular View 无法正常运行

javascript - 在 v-for 循环中仅检索一个元素的索引

javascript - Axios POST promise 无法按预期工作

Axios for REST api GET 中的 HTTP 失败