gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:49:23 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com