vue.js - 在 axios 承诺失败的情况下,如何有效地编写回退以从本地存储中获取对象?
问题描述
我正在尝试创建一个渐进式网络应用程序(我认为)。我已将标记中的按钮绑定到从 last.fm api 获取对象的方法
我想写一个回退,以防 API 没有响应从以前缓存的请求中获取相同的对象。
但是我注意到有两件事是错误的 1. cacheTopArtists 函数没有将我的对象正确保存到我的本地存储中。
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 我认为条件仍然得到满足,因为我在里面写的代码正在显示
- 我认为这对我的 mount() 函数产生了连锁反应,该函数应该在页面加载时用 localstorage 版本填充我的空对象
我尝试将 getTopArtists 方法移动到 mount() 对象,以便它在页面加载时运行
我也尝试过 setItem 而不对 myArtists 对象进行字符串化。
这是带有 js 和 html 的笔 https://codepen.io/anon/pen/GaEaKp
没有错误消息,除了 cachedArtists 为空
解决方案
cacheTopArtists
第一 -如果从未调用过,为什么要保存一些东西?它应该在请求成功后调用。
第二 - 如果您希望页面加载时的“回退”行为,那么您应该将缓存加载例程放到axios .get(...) .catch(...)
处理程序中。并getTopArtists
在你的mounted
钩子里打电话。
但最有效的方法是实现一个API模块,使用axios拦截器实现透明缓存,以防响应成功,拦截失败,返回缓存。
推荐阅读
- json - SQL JSON_VALUE 查询但没有路径名?
- google-chrome-headless - SElinux 阻止 Google-Chrome(无头)
- angular - 无法在角度电子邮件编辑器中读取未定义的属性“值”
- javascript - 如何删除 JavaScript 中句子的最后一个字符?
- html - CSS 变换:缩放使底部固定元素消失
- node.js - 以下代码是使用recaptcha 响应做某事的好习惯吗?
- python - 为什么我在 python 中为内置和定义的 FFT 得到不同的结果?
- webgl2 - WebGL2 未写入“out int [2]”结果的第二个输出
- excel - 如何按Excel或GSheet中第二列的值对第一列中具有相等值的列表进行排序?
- python - 如何查找文件中有多少个单词