【问题标题】:Axios result returns [object Promise]axios 结果返回 [object Promise]
【发布时间】:2021-07-23 05:48:47
【问题描述】:
我通过他们的 API 从 flicker 获取 feed 图片,
我有一个计算属性filteredImages:
computed: {
filteredImages: async function() {
return axios.get('https://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=' + this.search + '&nojsoncallback=1')
.then(function (response) {
return response.data.items;
})
}
},
当我在控制台记录 response.data.items 时,它会返回正确的结果集,但是当我在 HTML 中显示它时,它会显示 [object Promise]
这是Pen
知道为什么会这样吗?
【问题讨论】:
标签:
javascript
vue.js
axios
computed-properties
【解决方案1】:
最好的方法是将计算的内容放入mounted,而不是return response.data.items,您应该将其填写在一个变量中,例如如下:
data() {
return {
items: null,
}
},
mounted:{
let vm = this;
axios.get('https://api.flickr.com/services/feeds/photos_public.gne?format=json&tags='
+ this.search + '&nojsoncallback=1')
.then(function (response) {
vm.items = response.data.items;
})
}
在 html 中你可以简单地使用items 它会在准备好的时候显示
【解决方案2】:
您可以执行类似的操作从 HTTP 调用中获取属性并在 DOM 中呈现它们
new Vue({
el: "#app",
data: {
search: "",
filteredImages: "",
},
watch: {
search: function (newVal, oldVal) {
this.getItems();
},
},
methods: {
getItems: async function () {
try {
const { data } = await axios.get(
`https://api.flickr.com/services/feeds/photos_public.gne?format=jsonp&tags=${this.search}&nojsoncallback=1`
);
this.filteredImages = JSON.stringify(data.items)
} catch (error) {
console.error(error);
this.filteredImages = error.toString();
}
},
},
});
但是有一个issue,flickr 可以使用 JSONP 和 axios 或者 fetch 不支持它
您需要使用JSONP 模块
【解决方案3】:
计算道具不支持异步函数。此外,它们依赖于其他反应性道具来懒惰地计算它们。因此,每次需要获取过滤后的图像时,都需要直接调用此异步函数,并将它们放入 data prop 中的某个响应式 prop 中。