首页IT科技vue3使用路由(Vue3路由配置createRouter、createWebHistory、useRouter,useRoute)

vue3使用路由(Vue3路由配置createRouter、createWebHistory、useRouter,useRoute)

时间2025-05-28 12:50:56分类IT科技浏览7754
导读:目录...

目录

手动配置Vue-router环境:

组件内部跳转路由、传参useRouter,useRoute

Vue3和Vue2基本差不多,只不过需要将createRoutercreateWebHistoryvue-router中引入,再进行使用。

手动配置Vue-router环境:

1、下载包: npm i vue-router --save或者 npm i vue-router --S    或者用cdn引入

2、创建路由的js文件(路由、子路由、重定向、开启history模式)

      createRouter、createWebHistory

//路由文件 import { createRouter, createWebHistory } from vue-router //将createRouter、createWebHistory引入vue const routes = [ { path: /, //配置默认路由 name: home, //路由名 component: () => import("../views/home.vue"), //引入该路由使用的组件 }, { path: /a, name: a, component: () => import(../views/a.vue), redirect: /a/son1, children:[ //配置子路由 { path: /a/son1, //子路由路径前边必须写父路由路径 name: ason1, component: ()=>import("../views/a-son1.vue") } ] }, { path: /b, name: b, component: () => import(../views/b.vue), redirect: /b/son1, //重定向,进入/b路由时默认进入/b/son1 children:[ //配置子路由 { path: /b/son1, //子路由路径前边必须写父路由路径 name: bson1, component: ()=>import("../views/b-son1.vue") } ] } ] const router = createRouter({ //设置为history模式 history: createWebHistory(), routes }) export default router

3、将配置的路由js文件引入到main.js中

import { createApp } from vue import App from ./App.vue const app=createApp(App) import router from "./router/index.js" //引入配置路由文件 app.use(router)//记得在mount之前调用 app.mount(#app)

4、界面中使用router-view标签显示路由

组件内部跳转路由、传参useRouter,useRoute

vue3中,在组件内部跳转路由 需要使用useRouter,useRoute方法

useRoute相当于以前的this.$route 跳转路由

用法:

<template> <h1>aaa</h1> <router-view></router-view> <button @click="fn">从a路由跳转到b路由</button> </template> <script setup> import {useRouter} from "vue-router" let router=useRouter() //接收useRouter方法,在vue2中是直接使用router即可 let fn=()=>{ router.push({path:"/b",query:{name:"小狮子"}}) //path写跳转的路由,同样可以传参 } </script> <style scoped> h1{ width: 400px; height:200px; background-color:deeppink; } </style>

useRouter相当于this.$router  接受传参(query、params)

注意:1、请注意params只与name(路由文件里配置的路由name)搭配生效(不能使用path)

        2、只能在setup函数内使用

用法

<template> <h2>这是b-son1</h2> <button @click="fn">lookquery</button> </template> <script setup> import {useRoute} from "vue-router" //引入 let route=useRoute() console.log(route.query)//如果是params传参就用route.params接收 let fn=()=>{ //这不是setup函数内部,是取不到传参的,返回undefined let route=useRoute() console.log(route) } </script> <style scoped> h2{ width: 200px; height:100px; background-color:aliceblue; } </style>

结合前者代码进行验证,发现下图状况

 当我们进行页面跳转时成功获取了传参,但不在setup函数内使用useRouter是获取不了的

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
vue3.0 ts(Vue3通透教程【十一】初探TypeScript) 怎么优化网站结构(怎么优化网站设计)