如何从Vuejs的APi呼叫中获得响应



import axios from "axios";
export const routerid = async (itemId) =>
await axios.get("https://fakestoreapi.com/products?limit=" + itemId);

<template>
<div>
<div v-for="(item, key) in user" :key="key">
{{ item.price }} <br />
{{ item.description }} <br />
</div>
</div>
</template>
<script>
import { routerid } from "./routerid";
export default {
name: "User",
components: {},
data() {
return {
lists: [],
};
},
mounted() {
if (this.$route.params.id)
routerid(this.$route.params.id).then((r) => {
let obj = r.data;
this.lists = [{ ...obj }];
});
},
computed: {
user: function () {
return this.lists.filter((item) => {
return item.id === this.$route.params.id;
});
},
},
};
</script>

这是我的完整代码:-https://codesandbox.io/s/late-brook-eg51y3?file=/src/components/routerid.js

上面是我的api调用,url查询类似于url…./?limit="+"id

以上是我尝试过的逻辑。但不确定代码出了什么问题。获得空白屏幕。

请提供一些关于如何打电话的建议。如果还有其他问题,请检查一下我的代码。感谢

这都是关于扩展运算符的,您应该正确地在数组中扩展对象,下面的例子工作得很好。

<template>
<div>
<div v-for="(item, key) in user" :key="key">
{{ item.price }} <br />
{{ item.description }} <br />
</div>
</div>
</template>
<script>
import { routerid } from "./routerid";
export default {
name: "User",
components: {},
data() {
return {
lists: [],
};
},
mounted() {
if (this.$route.params.id)
routerid(this.$route.params.id).then((r) => {
let obj = r.data;
//changed from [{...obj}] to [...obj]
this.lists = [...obj];
});
},
computed: {
user: function () {
return this.lists.filter((item) => {
return item.id === this.$route.params.id;
});
},
},
};
</script>

您有两个问题。

1-首先,在for循环中使用user而不是lists

2-其次,你在重新调整的数据上使用排列运算符,这已经是一个数组了,所以你不需要这样做。

<template>
<div>
<div v-for="(item, key) in lists" :key="key">
{{ item.price }} <br />
{{ item.description }} <br />
</div>
</div>
</template>
<script>
import { routerid } from "./routerid";
export default {
name: "User",
components: {},
data() {
return {
lists: [],
};
},
mounted() {
if (this.$route.params.id)
routerid(this.$route.params.id).then((r) => {
this.lists = r.data;
});
},
computed: {
user: function () {
return this.lists.filter((item) => {
return item.id === this.$route.params.id;
});
},
},
};
</script>

最新更新