Vue.js 使用 axios 缓存 http 请求 [英] Vue.js cache http requests with axios

查看:53
本文介绍了Vue.js 使用 axios 缓存 http 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Vue.js 开发 PWA.当用户启动它时,需要来自另一个应用程序的一些信息.为此,我使用 axios:

I'm developing a PWA with Vue.js. When the user starts it, some information from another application is needed. For this, i'm using axios:

let url = 'url';
axios.get(url).then((response) => {
  callback(response.data)
})

只要用户在线,它就可以正常工作.如果网络连接正常,则应通过 URL 检索数据,如果没有 Internet 连接,则应从缓存加载数据.这怎么可能?

it's working fine as long as the user is online. if the network connection is OK, data should be retrieved by the URL, and if there is no internet connection, data should be loaded from cache. How is this possible?

推荐答案

你可以查看这个扩展https://github.com/kuitos/axios-extensions

这里是基本用法示例,希望对您有帮助

Here is the basic usage example, I hope it helps

import axios from 'axios';
import { cacheAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
    baseURL: '/',
    headers: { 'Cache-Control': 'no-cache' },
    // cache will be enabled by default
    adapter: cacheAdapterEnhancer(axios.defaults.adapter)
});

http.get('/users'); // make real http request
http.get('/users'); // use the response from the cache of previous request, without real http request made
http.get('/users', { cache: false }); // disable cache manually and the the real http request invoked

这篇关于Vue.js 使用 axios 缓存 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆