Vue Router不要再使用params传参了,params获取不到参数,官方删除params传参

3,047 阅读1分钟

问题描述

之前说过,vue路由传参有两种方式,分别是queryparams;query是明文,params是隐藏的;
今天在使用params的时候发现获取不到参数了

1、路由配置

{
    path:'/about',
    name:'about',
    component:About
}

2、跳转

this.$router.push({
    name:'about',
    params:{
        id:1
    }
})

3、接收

console.log(this.$route.params);

4、结果:
得到一个警告和空对象
在这里插入图片描述

原因分析:

点开链接后发现了原因, 点击查看更新日志
在这里插入图片描述在这里插入图片描述也就是说,从Vue Router的2022-8-22 这次更新后,我们使用上面的方式在新页面无法获取

解决方案:

vue也给我们提出了代替方案:

  1. 使用 query 的方式传参
  2. 将参数放在 pinia 或 vuex仓库里
  3. 使用动态路由匹配
  4. 传递 state,在新页面使用 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’ ,中这三个参数你都必须传递,否则会报错:
在这里插入图片描述

使用HistoryAPI方式传递和接收

在跳转前的页面使用 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>

image.png