Vue.js路由刷新时/dashboard/me页面数据丢失且请求返回304的问题求助
Vue.js路由刷新时/dashboard/me页面数据丢失且请求返回304的问题求助
各位大佬好,我最近开发Vue.js应用时遇到了个棘手问题,想请教下大家:
我用Vue Router做路由管理、Axios请求后端数据,目前有两个核心路由:/dashboard(父路由,对应Dashboard组件,作为所有子路由的容器)和它的子路由/dashboard/me(对应AboutMePage组件)。/dashboard页面不管怎么刷新,数据都能正常加载显示,但一刷新/dashboard/me页面,Dashboard组件里的数据就直接丢失了,而且Axios请求返回304 Not Modified状态码。
我已经尝试过的操作
调整Vue Router路由配置
初始的路由配置是这样的:
const routes: RouteRecordRaw[] = [ { path: '/dashboard', component: Dashboard, name: 'dashboard', children: [{ path: 'me', name: 'me', component: AboutMePage }], }, ];
一开始子路由me用的是相对路径path: 'me',后来我改成绝对路径path: '/me',刷新页面后数据就正常了,但这样路由变成了/me而非我需要的/dashboard/me,破坏了原本的URL嵌套结构。
配置Axios禁用缓存
我怀疑是缓存导致的304问题,所以在Axios实例里加了禁用缓存的请求头,但问题依然存在:
export const axiosInstance: AxiosInstance = axios.create({ baseURL: 'v1/', timeout: 1000, headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', // 尝试禁用缓存 // 'Pragma': 'no-cache', // 也试过添加这个字段 // 'Expires': '0', // 还试过强制标记缓存过期 } })
/dashboard页面的请求完全正常,就是刷新/dashboard/me时会返回304,直接导致数据丢失。
检查Vite代理配置
我的Vite代理配置用来转发前端请求到后端,目前看起来没有明显问题:
export default defineConfig({ plugins: [vue()], server: { proxy: { '/v1': { target: 'http://localhost:3001/', changeOrigin: true, secure: false, ws: true, configure: (proxy, _options) => { proxy.on('error', (err, _req, _res) => { console.log('proxy error', err); }); proxy.on('proxyReq', (proxyReq, req, _res) => { console.log('Sending Request to the Target:', req.method, req.url); }); proxy.on('proxyRes', (proxyRes, req, _res) => { console.log('Received Response from the Target:', proxyRes.statusCode, req.url); }); }, } } } })
我的几个核心疑问
- 为什么把子路由从相对路径改成绝对路径,会影响数据请求的行为?
- 为什么
/dashboard页面刷新没问题,/dashboard/me刷新就丢数据? - 有没有办法在保持
/dashboard/me这个URL结构的前提下,解决304问题,确保每次刷新都能拿到最新数据?
麻烦各位大佬帮忙分析下,谢谢了!
备注:内容来源于stack exchange,提问作者Asking
相关产品推荐
相关产品推荐

