[Vue Router warn]: Discarded invalid param(s) “id“ when navigating. Seexxxxxxxfor more details

 警告信息建议访问的链接

场景:

当我 在vue3 组合式api中尝试使用name+params去路由跳转并传递参数的时候,出现警告信息,并且接收不到params的参数。代码如下:

a页面跳转b页面

//a页面

<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>
//b页面

<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>

点击链接查看到更新日志

也就是说,从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 方式传递和接收)

5.使用 meta 原信息方式传递 (此方式更适用于路由守卫)

使用动态路由匹配

如果传递参数较少的情况下,可以尝试使用下面这种方式,只要修改一下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' ,中这三个参数你都必须传递,否则会报错:

使用 History API 方式传递和接收

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

//a页面
<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>
//b页面
<template>
  <div>{
   
   { historyParams }}</div>
</template>

<script setup lang="ts">

const historyParams = history.state.params
console.log('history.state', history.state)
</script>

 内容来源于作者: 

lioayi

文章地址: https://www.cnblogs.com/liao-yi/articles/17028269.html

猜你喜欢

转载自blog.csdn.net/m0_57033755/article/details/129927829
今日推荐