Vue3 使用 Vue Router 时,prams 传参失效和报错问题

Discarded invalid param(s) "id", "name", "age" when navigating

我尝试使用 prams 传递数据

复制代码
<script setup>
import { useRouter } from 'vue-router'
    
const router = useRouter()
const params = { id: '1', name: 'ly', phone: 13246566476, age: 23 }
const toDetail = () => router.push({ name: 'detail', params })

</script>

<template>
  <el-button type="danger" @click="toDetail">查看情页</el-button>
</template>

在接收页面尝试渲染 prams 传递的数据:

复制代码
<template>
  <div>姓名:{{ route.params?.name }}</div>
  <div>电话:{{ route.params?.phone }}</div>
  <div>年龄:{{ route.params?.age }}</div>
</template>

<script setup>
import { useRoute } from 'vue-router'
const route = useRoute()
</script>

当我跳转页面时,得到的 prams 数据为空 ,控制台也出现了 Vue Router 的警告

点开链接后发现了原因, 点击查看更新日志

也就是说,从Vue Router的2022-8-22 这次更新后,我们使用上面的方式在新页面无法获取:

vue也给我们提出了解决方案:

  1. 使用 query 的方式传参

    只要改成query 传参就好了,注意query传参只能用路由表中的 path ,不是 name ,并且所有参数都会显示在URL 地址上。

    复制代码
    <script setup>
    import { useRouter } from 'vue-router'
        
    const router = useRouter()
    const query = { id: '1', name: 'ly', phone: 13246566476, age: 23 }
    const toDetail = () => router.push({  path: '/detail', query })
    
    </script>
    <template>
      <el-button type="danger" @click="toDetail">查看情页</el-button>
    </template>
  2. 将参数放在 pinia 或 vuex仓库里

  3. 使用动态路由匹配

  4. 传递 state,在新页面使用 History API 接收参数\](#使用 History API 方式传递和接收)

使用动态路由匹配

如果传递参数较少的情况下,可以尝试使用下面这种方式,只要修改一下path定义部分就可以了:

复制代码
// params 传递的参数: { id: '1', name: 'ly', phone: 13246566476, age: 23 }

{
      path: '/detail/:id/:name/:phone/:age',
      name: 'detail',
      component: () => import('@/views/detail/index.vue')
}

查看页面效果,控制台警告也消失了:

注意,如果使用使用了这种动态路由匹配方式, path: '/detail/:id/:name/:phone/:age' ,中这三个参数你都必须传递,否则会报错:

个人觉得这么写很鸡肋: 如果不把params参数写在路由路径中无法得到 params 参数,这种方式的params参数又会显示在地址栏。虽然不算弃用params, 但是每次把params参数写在路由路径中是很麻烦的一件事。

使用 History API 方式传递和接收

在跳转前的页面使用 state 参数:

复制代码
<script setup>
import { useRouter } from 'vue-router'
    
const router = useRouter()

const params = { id: '1', name: 'ly', phone: 13246566476, age: 23 }
const toDetail = () => router.push({ name: 'detail', state: { params } })

</script>

<template>
  <el-button type="danger" @click="toDetail">查看情页</el-button>
</template>

跳转的后页面接收:

复制代码
<template>
  <div>{{ historyParams }}</div>
</template>

<script setup lang="ts">

const historyParams = history.state.params
console.log('history.state', history.state)
</script>
相关推荐
崔庆才丨静觅5 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60616 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了6 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅6 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅7 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅7 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment7 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅7 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊7 小时前
jwt介绍
前端
爱敲代码的小鱼8 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax