面试题答案
一键面试实现思路
- 定义一个缓存对象,用于存储接口数据。
- 在每次请求前,先检查缓存中是否有对应的数据。
- 如果有且在有效时间内,则直接返回缓存数据;否则发起网络请求,并将新数据存入缓存。
代码示例
- 安装 axios:如果项目未安装
axios
,可以使用npm install axios
或yarn add axios
进行安装。 - 创建缓存逻辑:可以在项目中的一个独立文件(如
http.js
)中定义缓存逻辑。
import axios from 'axios';
// 缓存对象
const cache = {};
// 缓存有效时间(单位:毫秒),这里设置为10秒
const cacheDuration = 10 * 1000;
axios.interceptors.request.use(config => {
const { url } = config;
const cached = cache[url];
if (cached && Date.now() - cached.timestamp < cacheDuration) {
return Promise.resolve(cached.data);
}
return config;
});
axios.interceptors.response.use(response => {
const { config: { url }, data } = response;
cache[url] = {
data,
timestamp: Date.now()
};
return response;
});
export default axios;
- 在Vue组件中使用
<template>
<div>
<button @click="fetchUserInfo">获取用户信息</button>
<div v-if="userInfo">
<p>用户名: {{ userInfo.name }}</p>
<p>其他信息: {{ userInfo.otherInfo }}</p>
</div>
</div>
</template>
<script>
import axios from './http';
export default {
data() {
return {
userInfo: null
};
},
methods: {
async fetchUserInfo() {
try {
const response = await axios.get('/api/userInfo');
this.userInfo = response;
} catch (error) {
console.error('获取用户信息失败', error);
}
}
}
};
</script>
上述代码通过 axios
的拦截器实现了简单的缓存机制,在 request
拦截器中检查缓存,在 response
拦截器中更新缓存。在Vue组件中使用这个经过封装的 axios
实例进行请求,就可以实现短时间内重复请求接口直接从缓存获取数据。