给路由添加query参数,页面不刷新;

182 阅读1分钟

使用场景如下,添加功能,添加后,后端返回一个id,前端把id存入一个变量,同时添加到路由的query中;并且不能刷新页面,因为刷新体验效果不好;

这些操作成功后,我手动刷新,可以走查询详情接口;并且返回之前填写的数据;

const addQueryParam = id => {
    const newQuery = {
        ...route.query, // 保留原有的 query 参数
        id: id, // 新增的 query 参数
    }
    //我的本地路径http://localhost:8080/#/addCustomer
    // 构建新的 URL,将 query 参数放在 # 后面的路径上
    const basePath = window.location.hash.split('?')[0] // 获取 # 之前的部分,即路径
    const newUrl = `${window.location.origin}/${basePath}?${new URLSearchParams(newQuery).toString()}`

    // 使用 replaceState 更新 URL,保留现有的 history.state
    window.history.replaceState(
        window.history.state, // 保留现有的 history.state
        '',
        newUrl,
    )
}