在使用vue-router4中params 进行路由组件之间传参接收不了并出现如下错误
index.vue:10 [Vue Router warn]: Discarded invalid param(s) "name" when navigating. See
https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22 for more details.
查看相应的CHANGELOG
后发现由于刷新页面会导致params
丢失,因此这种传参方式被废弃了。
CHANGELOG
中提供了几种方案,我选择一种比较容易理解且相似的举例,其他方案可自行翻阅使用
通过history 的state 传递与接收
// 传参
<script setup>
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
console.log("query", route.query);
</script>
<template>
<div class="container">
//将params替换为state,注意此处的state里面的参数名叫name
<button @click="() => router.push({ name: 'Mine', state: { name: 2 } })">
跳转到我的页面
</button>
</div>
</template>
// 接收
<script setup>
import { useRouter } from "vue-router";
const router = useRouter();
// 通过history.state这个对象去获取之前的name
console.log("history.state", history.state);// => { "back": "/home?id=1", "current": "/mine","forward": null,"replaced": false,"position": 15,"scroll": null,"name": 2}
console.log("history.state.name", history.state.name);// => 2
</script>
<template>
<div class="container">
<button @click="() => router.push({ path: '/home', query: { id: 1 } })">
跳转到首页
</button>
</div>
</template>