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 - Innerhtml 创建文本区域字段

javascript - Vue 2.0 和 Rails 5 : Declarative Rendering not Reactive

javascript - 数组/列表长度为零但数组不为空

node.js - Fetch API 在 POSTMAN 和 Express 服务器上工作,但在 React js 上不起作用

javascript - 使用 stringify 将对象设置和获取到本地存储?

javascript - 如何展开/折叠段落

javascript - 编程组件上的 Vue 响应式(Reactive) Prop

javascript - 过滤 Axios 响应

javascript - Bottle 不识别 Axios.js json post

javascript - this.value 和 $(this).val() 有什么区别?