解决vue3 路由query传参刷新后数据丢失的问题

发布于:2025-05-01 ⋅ 阅读:(26) ⋅ 点赞:(0)

前言:在页面刷新的时候,路由query数据会被清空,网上很多方法说query传参可以实现,反正我是没有实现

思路:将数据保存到本地,通过 “ ?” 进行判断是否有数据,页面销毁的时候删除本地的数据

有数据就保存到本地

无数据就获取本地的数据

布置:

1.父组件

const sampleDetailClick = (routerId) => {

  router.push({

    path: '/informationEntry/specimenDetail',

    query: { routerId },

  });

};

2.封装公共的处理方法,方便后期使用

export function initRequest(path:any) {  

  let url = window.location.href.split("?");

  if (url[1]) {

      localStorage.setItem(url[0], url[1])

      const paramsObj = stringToObject(url[1]);

      return { isParams: true, paramsObj }

  } else{

      let params = localStorage.getItem(url[0]) || '';

      const newUrl = window.location.origin + window.location.pathname + '?' + params;

      window.history.replaceState({}, '', newUrl);

      const paramsObj = stringToObject(params);

      return { isParams: false, paramsObj }

  }

}

引入

import { initRequest } from '@/utils/utils.ts'

 3.在子组件里面使用

import { reactive, ref, onMounted, onBeforeUnmount } from 'vue';
import { initRequest } from '@/utils/utils.ts'
const route = useRoute();
let { id } = route.query;

let currentUrl = window.location.href.split("?");
onMounted(() => {

  const obj = initRequest()
  if (obj) ({ id } = obj.paramsObj);
  openAddModal();  //获取详情
})
onBeforeUnmount(() => { localStorage.removeItem(currentUrl[0]); })

4.刷新验证功能,在本地里面查看


网站公告

今日签到

点亮在社区的每一天
去签到