Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vue.js 在axios承诺失败的情况下,如何有效地编写回退以从localstorage获取对象?_Vue.js_Local Storage_Axios - Fatal编程技术网

Vue.js 在axios承诺失败的情况下,如何有效地编写回退以从localstorage获取对象?

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 } }

我正在尝试创建一个进步的web应用程序(我想)。 我已将标记中的一个按钮绑定到从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设置为空,但我认为在显示我在其中编写的代码时仍然满足了该条件

  • 我认为这对我的mounted()函数有一个敲打效应,它应该在页面加载时用localstorage版本填充我的空对象
  • 我已经尝试将getOpartists方法移动到mounted()对象,以便它在页面加载时运行

    我还尝试了setItem,但没有对myArtists对象进行字符串化

    这是带有js和html的笔


    没有错误消息,除了cachedArtists为null(第一个)

    为什么
    cacheTopArtists
    如果从未调用它,就应该保存它?请求成功后应调用它

    第二,如果您想在页面加载上实现“回退”行为,那么应该将缓存加载例程放到axios.get(…).catch(…)处理程序中。并在
    挂载的
    钩子中调用
    getTopArtists

    但最有效的方法是实现API模块,并使用axios拦截器在成功响应和拦截失败并返回缓存时实现透明缓存


    你好,伊万,谢谢你的建议。你说得对,我曾尝试立即缓存艺术家,但它不允许我在“.then”(response=>(this.myArtists=response.data.topartists.artist))”之后立即将艺术家缓存到本地存储中,但我可以执行多个then()函数