命名路由,编程式跳转
const routes:RouteRecordRaw[] = [{path:'/',name:'A',component: ()=> import('../A.vue')},{path:'/B',name:'B',component: ()=> import('../B.vue')},
]
- 通过name进行跳转
<template><div><router-link :to="{name:'A'}">A路由</router-link><router-link :to="{name:'B'}" style="margin-left:10px">B路由</router-link></div>
</template>
- 通过编程式跳转
<template><div><button @click="ASkip('/')">A路由跳转</button><button @click="BSkip('/B')" style="margin-left:10px">B路由跳转</button></div><router-view></router-view>
</template><script setup lang="ts">import { useRouter } from 'vue-router'
const router = useRouter()const ASkip = (url:string)=>{// 字符串// router.push(url)// 对象形式, 可进行传参 path 对应的 query name 对应的 paramsrouter.push({path:url,query:{name:'我是path跳转'}})
}// 通过query进行传参数,相关组件接受如下
import { useRoute } from 'vue-router'const route = useRoute()console.log('routeA:',route.query)// 通过name传参数,vue-router 使用的是v4.x
const BSkip = (url:string)=>{// 字符串// router.push(url)// 对象形式, 可进行传参 path 对应的 query name 对应的 paramsrouter.push({name:url,params:{name:'我是name跳转'}})
}import { useRoute } from 'vue-router'const route = useRoute()
// 发现在B组件中获取到的router.params 值是{}对象,拿不到值,且控制台报出警告:[Vue Router warn]: Discarded invalid param(s) "username" when navigating
console.log('routeB:',route.params)// 若是非得通过name传参,可以使用如下方法
const BSkip = (url:string)=>{router.push({name:url,state: {username:'我是name跳转',age:18}})
}// B组件接收参数:通过history.state可以拿到username,age的值
console.log('routeB:',history.state)
问题:name方式传参有如下警告:[Vue Router warn]: Discarded invalid param(s) “username” when navigating,各位大佬有解决办法麻烦告知一声。