Vue3 使用router,params传参为空,怎么办?

git vuejs router
从Vue Router的2022-8-22 更新后,我们使用param传参在新页面无法获取数据。
可以有其他解决办法:

1.使用query方式传参。

只需要将params变为query就行,注意query传参只能用路由表中的path,不是name,并且所有参数都会显示在URL地址上。

<template>
	<span
		class="battery-capacity"
        @click="goBatteryClusterInfo(index)">
     </span>
</template>
<script setup lang="ts">
import {
    
     useRouter } from "vue-router"

const router = userRouter;
const goBatteryClusterInfo = (index: number): void => {
    
    
    let param = index + 1;
    router.push({
    
    
      name: "batteryClusterDetail",
      query: {
    
     param },
    });
};
</script>

1.使用 History API 方式传递和接收

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

<template>
	<span
		class="battery-capacity"
        @click="goBatteryClusterInfo(index)">
     </span>
</template>
<script setup lang="ts">
import {
    
     useRouter } from "vue-router"

const router = userRouter;
const goBatteryClusterInfo = (index: number): void => {
    
    
    let param = index + 1;
    // 使用 History API 方式传递和接收,在跳转前的页面使用 state 参数
    router.push({
    
    
      name: "batteryClusterDetail",
      state: {
    
     param },
    });
};
</script>

在另一个页面中获取数据

// 获取history中我们上个页面保存的数据
const historyParam = history.state.param;
console.log(history.state,"history.state")

猜你喜欢

转载自blog.csdn.net/weixin_45288172/article/details/129931179