当前位置:   article > 正文

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

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

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

我尝试使用 prams 传递数据

  1. <script setup>
  2. import { useRouter } from 'vue-router'
  3. const router = useRouter()
  4. const params = { id: '1', name: 'ly', phone: 13246566476, age: 23 }
  5. const toDetail = () => router.push({ name: 'detail', params })
  6. </script>
  7. <template>
  8. <el-button type="danger" @click="toDetail">查看情页</el-button>
  9. </template>

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

  1. <template>
  2. <div>姓名:{{ route.params?.name }}</div>
  3. <div>电话:{{ route.params?.phone }}</div>
  4. <div>年龄:{{ route.params?.age }}</div>
  5. </template>
  6. <script setup>
  7. import { useRoute } from 'vue-router'
  8. const route = useRoute()
  9. </script>

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

Vue Router 的警告

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

S1

S2

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

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

  1. 使用 query 的方式传参

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

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

  3. 使用动态路由匹配

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

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

使用动态路由匹配

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

  1. // params 传递的参数: { id: '1', name: 'ly', phone: 13246566476, age: 23 }
  2. {
  3. path: '/detail/:id/:name/:phone/:age',
  4. name: 'detail',
  5. component: () => import('@/views/detail/index.vue')
  6. }

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

image-20230105162347660

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

image-20230105163743993

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

使用 History API 方式传递和接收

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

  1. <script setup>
  2. import { useRouter } from 'vue-router'
  3. const router = useRouter()
  4. const params = { id: '1', name: 'ly', phone: 13246566476, age: 23 }
  5. const toDetail = () => router.push({ name: 'detail', state: { params } })
  6. </script>
  7. <template>
  8. <el-button type="danger" @click="toDetail">查看情页</el-button>
  9. </template>

跳转的后页面接收:

  1. <template>
  2. <div>{{ historyParams }}</div>
  3. </template>
  4. <script setup lang="ts">
  5. const historyParams = history.state.params
  6. console.log('history.state', history.state)
  7. </script>

image-20230105164119984

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号