Vue.js 在axios承诺失败的情况下,如何有效地编写回退以从localstorage获取对象?
我正在尝试创建一个进步的web应用程序(我想)。 我已将标记中的一个按钮绑定到从last.fm api获取对象的方法 我想写一个回退,以防API没有响应从以前缓存的请求中获取相同的对象 然而,我注意到两件事是错误的 1.cacheTopArtists函数未将我的对象正确保存到本地存储中Vue.js 在axios承诺失败的情况下,如何有效地编写回退以从localstorage获取对象?,vue.js,local-storage,axios,Vue.js,Local Storage,Axios,我正在尝试创建一个进步的web应用程序(我想)。 我已将标记中的一个按钮绑定到从last.fm api获取对象的方法 我想写一个回退,以防API没有响应从以前缓存的请求中获取相同的对象 然而,我注意到两件事是错误的 1.cacheTopArtists函数未将我的对象正确保存到本地存储中 new Vue({ el: '#LastFM', data() { return { myArtists: null } }
new Vue({
el: '#LastFM',
data() {
return {
myArtists: null
}
},
mounted() {
loadCachedTopArtists: {
if (localStorage.cachedArtists) {
this.myArtists = localStorage.cachedArtists;
}
}
},
methods: {
getTopArtists: function(e) {
axios
.get("https://ws.audioscrobbler.com/2.0/?api_key=2c5c5c19e5d21ce9cf86b13712a1bbed&format=json&method=user.getTopArtists&user=El_Mayo&period=overall&limit=200")
.then(response => (this.myArtists = response.data.topartists.artist))
.catch(error => console.log(error))
//if there is an error nothing should happen an this.myArtists is still equal to the localStorage.cachedArtists from line 31 (?);
},
cacheTopArtists: function(e) {
localStorage.setItem('cachedArtists', JSON.stringify(this.myArtists));
}
},
computed: {
backgroundImage: function() {
return (artist) => artist.image.find(size => size.size === 'large')['#text']
}
}
})
cachedArtists密钥存在,但为空。尽管我将myArtists:null设置为空,但我认为在显示我在其中编写的代码时仍然满足了该条件
没有错误消息,除了cachedArtists为null(第一个)为什么
cacheTopArtists
如果从未调用它,就应该保存它?请求成功后应调用它
第二,如果您想在页面加载上实现“回退”行为,那么应该将缓存加载例程放到axios.get(…).catch(…)处理程序中。并在挂载的钩子中调用getTopArtists
但最有效的方法是实现API模块,并使用axios拦截器在成功响应和拦截失败并返回缓存时实现透明缓存
你好,伊万,谢谢你的建议。你说得对,我曾尝试立即缓存艺术家,但它不允许我在“.then”(response=>(this.myArtists=response.data.topartists.artist))”之后立即将艺术家缓存到本地存储中,但我可以执行多个then()函数