当前位置:   article > 正文

vue3 vue-router

vue3 vue-router

Vue 路由允许我们通过不同的 URL 访问不同的内容。通过 Vue 可以实现多视图的单页Web应用

一、入门(安装及配置)

1. 安装vue-router

npm i vue-router --save

2. 配置vue-router

新建 router 文件夹

路径:/src/router

新建 index.js 文件

路径:/src/router/index.js

index.js

  1. import {createRouter,createWebHistory } from 'vue-router'
  2. const routes = [
  3. {
  4. path:'/',
  5. component:() => import('../pags/login.vue')
  6. }
  7. ]
  8. const router = createRouter({
  9. history:createWebHistory(),
  10. routes //路由信息
  11. })
  12. export default router

main.js

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import router from './router'
  4. createApp(App).use(router).mount('#app')

App.js

  1. <template>
  2. <router-view/>
  3. </template>
  4. <script>
  5. export default {
  6. }
  7. </script>
  8. <style>
  9. </style>

小满Router(第一章入门)_小满zs的博客-CSDN博客

第二章 命名路由-编程式导航(跳转)

除了 path 之外,你还可以为任何路由提供 name。这有以下优点:

  • 没有硬编码的 URL
  • params 的自动编码/解码。
  • 防止你在 url 中出现打字错误。
  • 绕过路径排序(如显示一个)
  1. const routes:Array<RouteRecordRaw> = [
  2. {
  3. path:"/",
  4. name:"Login",
  5. component:()=> import('../components/login.vue')
  6. },
  7. {
  8. path:"/reg",
  9. name:"Reg",
  10. component:()=> import('../components/reg.vue')
  11. }
  12. ]

router-link跳转方式需要改变 变为对象并且有对应name

  1. <h1>小满最骚</h1>
  2. <div>
  3. <router-link :to="{name:'Login'}">Login</router-link>
  4. <router-link style="margin-left:10px" :to="{name:'Reg'}">Reg</router-link>
  5. </div>
  6. <hr />

编程式导航

除了使用 <router-link> 创建 a 标签来定义导航链接,我们还可以借助 router 的实例方法,通过编写代码来实现。

1.字符串模式

  1. import { useRouter } from 'vue-router'
  2. const router = useRouter()
  3. const toPage = () => {
  4. router.push('/reg')
  5. }

2.对象模式

  1. import { useRouter } from 'vue-router'
  2. const router = useRouter()
  3. const toPage = () => {
  4. router.push({
  5. path: '/reg'
  6. })
  7. }

3.命名式路由模式

  1. import { useRouter } from 'vue-router'
  2. const router = useRouter()
  3. const toPage = () => {
  4. router.push({
  5. name: 'Reg'
  6. })
  7. }

a标签跳转

直接通过a href也可以跳转但是会刷新页面

 <a href="/reg">rrr</a>

参考:小满Router(第二章-命名路由-编程式导航)_小满zs的博客-CSDN博客

 第三章 历史记录

replace的使用 

采用replace进行页面的跳转会同样也会创建渲染新的Vue组件,但是在history中其不会重复保存记录,而是替换原有的vue组件;

该方法的原理是: 替代

router.replace 跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。

router-link 使用方法

  1. <router-link replace to="/">Login</router-link>
  2. <router-link replace style="margin-left:10px" to="/reg">Reg</router-link>

编程式导航

  1. <button @click="toPage('/')">Login</button>
  2. <button @click="toPage('/reg')">Reg</button>
  1. import { useRouter } from 'vue-router'
  2. const router = useRouter()
  3. const toPage = (url: string) => {
  4. router.replace(url)
  5. }

横跨历史

该方法采用一个整数作为参数,表示在历史堆栈中前进或后退多少步

  1. <button @click="next">前进</button>
  2. <button @click="prev">后退</button>
  1. const next = () => {
  2. //前进 数量不限于1
  3. router.go(1);
  4. }
  5. const prev = () => {
  6. //后退
  7. //router.go(-1);
  8. router.back();
  9. }

参考小满Router(第三章-历史记录)_小满zs的博客-CSDN博客_router 历史记录

第四章 路由传参

useRouter与useRoute的区别

useRouter是全局对象,用来传入参数。useRoute是当前对象,用来接收参数

useRouter介绍及使用

1. router是VueRouter的一个对象,通过Vue.use(VueRouter)和VueRouter构造函数得到一个router的实例对象,这个对象中是一个全局的对象,包含了所有的路由包含了许多关键的对象和属性。例如history对象

  • $router.push({path:’/path’}); 本质是向history栈中添加一个路由,在我们看来是 切换路由,但本质是在添加一个history记录
  • $router.replace({path:’/path’}); 替换路由,没有历史记录
     

useRoute介绍及使用

2. route是一个跳转的路由对象,每一个路由都会有一个route对象,是一个局部的对象,可以获取对应的name,path,params,query等

  • $route.path
  • 字符串,等于当前路由对象的路径,会被解析为绝对路径,如 “/index/” 。
  • $route.params
  • 对象,包含路由中的动态片段和全匹配片段的键值对
  • $route.query
  • 对象,包含路由中查询参数的键值对。例如,对于 /index?id=1 ,会得到 $route.query.id == 1。

params传参合query传参的区别

1. params参数在地址栏中不会显示,query会显示

  1. this.router.push({path:'/customList'params:{id:6}})
  2. this.router.push({path:'/customList'query:{id:6}})

params: http://localhost:8080/#/customList
query:http://localhost:8080/#/customList?id=6

2.网页刷新后params参数会不存在

Params路由传参

编程式导航 使用router.push 或者 replace 的时候 改为对象形式并且只能使用name,path无效,然后传入params

使用useRouter传入参数(params)

语法:

router.push({ name:'listSecond', params:{ id, tips}})

  1. <template>
  2. <div>
  3. <div class="list-style"
  4. v-for="item in listItem"
  5. :key="item.id"
  6. @click="handlerId(item?.id,item?.tips)"
  7. >{{item.title}}</div>
  8. </div>
  9. </template>
  10. <script>
  11. import {defineComponent, ref} from 'vue'
  12. import {useRouter} from 'vue-router'
  13. export default defineComponent({
  14. setup() {
  15. const listItem = ref([
  16. {
  17. title:'标题一',
  18. id:1,
  19. tips:'title-one'
  20. },
  21. {
  22. title:'标题二',
  23. id:2,
  24. tips:'title-second'
  25. }
  26. ])
  27. const router = useRouter();
  28. const handlerId =(id,tips) =>{
  29. //params的属性值只能为 对象
  30. router.push({name:'listSecond',params:{id,tips}})
  31. }
  32. return{listItem,handlerId}
  33. }
  34. })
  35. </script>

使用useRoute接收参数(params)

  1. import { useRoute } from 'vue-router';
  2. const route = useRoute()
<div>ID:{{ route.params?.id }}</div>

动态路由传参
很多时候,我们需要将给定匹配模式的路由映射到同一个组件。例如,我们可能有一个 User 组件,它应该对所有用户进行渲染,但用户 ID 不同。在 Vue Router 中,我们可以在路径中使用一个动态字段来实现,我们称之为 路径参数 。

路径参数 用冒号 : 表示。当一个路由被匹配时,它的 params 的值将在每个组件
因为用params路由传参,刷新界面会失去参数。配置动态路由之后就刷新后依然存在。

  1. {
  2. path:'/listFirst',
  3. name:'listFirst',
  4. component:()=>import('../pages/transmitInfo/list-first')
  5. },
  6. {
  7. path:'/listSecond/:id/:tips',//配置动态路由参数 :id、:tips
  8. name:'listSecond',
  9. component:()=>import('../pages/transmitInfo/list-second'),
  10. }

Query路由传参

编程式导航 使用router push 或者 replace 的时候 改为对象形式新增query 必须传入一个对象 

语法:

 router.push({ path:'/listSecond',query:{id,tips}})

使用useRouter传入参数(params) 

  1. const router = useRouter();
  2. const handlerId =(id,tips) =>{
  3. router.push({path:'/listSecond',query:{id,tips}})
  4. }

 使用useRoute接收参数(params)

  1. import { useRoute } from 'vue-router';
  2. const route = useRoute()
<div>ID:{{ route.query?.id }}</div>
  1. import { useRoute } from 'vue-router';
  2. import { data } from './list.json'
  3. const route = useRoute()
  4. const item = data.find(v => v.id === Number(route.params.id))

二者的区别

  1. query 传参配置的是 path,而 params 传参配置的是name,在 params中配置 path 无效
  2. query 在路由配置不需要设置动态路由参数,而 params 必须设置
  3. query 传递的参数会显示在地址栏中
  4. params传参刷新会无效(设置动态路由参数后有效),但是 query 会保存传递过来的值,刷新不变 ;
  5. 路由配置

第五章 嵌套路由

一些应用程序的 UI 由多层嵌套的组件组成。在这种情况下,URL 的片段通常对应于特定的嵌套组件结构,例如:导航栏右侧显示 另一页面(父子路由)

  1. const routes: Array<RouteRecordRaw> = [
  2. {
  3. path:'/search',
  4. component:search,
  5. redirect:'/search/htmlcontent',
  6. children:[
  7. {
  8. // 子路由的path里面的值不需要加 /
  9. path:'htmlcontent',
  10. component:()=>import('../components/serch/htmlcontent')
  11. },
  12. {
  13. path:'csscontent',
  14. component:()=>import('../components/serch/csscontent')
  15. }
  16. ]
  17. }
  18. ]

如你所见,children 配置只是另一个路由数组,就像 routes 本身一样。因此,你可以根据自己的需要,不断地嵌套视图。children里面的path属性值不要加 /

TIPS:不要忘记写router-view

router-view 当你的路由path 与访问的地址相符时,会将指定的组件替换该 router-view

  1. <div>
  2. <router-view></router-view>
  3. <div>
  4. //不要忘记 需要写上父路由
  5. <router-link to="/search">login</router-link>
  6. <router-link style="margin-left:10px;" to="/search/htmlcontent">htmlcontent</router-link>
  7. </div>
  8. </div>

方式二 使用 ruoter.push

  1. <template>
  2. <div>
  3. <div class="search-style">
  4. <div class="nav-left">
  5. <div class="navitem-style" v-for="item in navlist" :key="item.id" @click="handerNav(item.path)">{{item.title}}</div>
  6. </div>
  7. <div class="nav-content">
  8. <router-view></router-view>
  9. </div>
  10. </div>
  11. </div>
  12. </template>
  13. <script>
  14. import {defineComponent,ref} from 'vue'
  15. import {useRouter} from 'vue-router'
  16. export default defineComponent({
  17. setup(){
  18. const route = useRouter();
  19. const navlist = ref([
  20. {
  21. title:'HTML',
  22. id:1,
  23. path:'/htmlcontent'
  24. },
  25. {
  26. title:'CSS',
  27. id:2,
  28. path:'/csscontent'
  29. }
  30. ])
  31. const handerNav =(path)=>{
  32. route.push('/search'+path);
  33. }
  34. return{navlist,handerNav}
  35. }
  36. })
  37. </script>

参考   小满Router(第六章-命名视图)_小满zs的博客-CSDN博客

第六章 命名视图(同一级(组件)中展示更多的路由视图)

命名视图可以在同一级(同一个组件)中展示更多的路由视图,而不是嵌套显示。 命名视图可以让一个组件中具有多个路由渲染出口,这对于一些特定的布局组件非常有用。 命名视图的概念非常类似于“具名插槽”,并且视图的默认名称也是 default。

一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。确保正确使用 components 配置 (带上 s)

  1. import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
  2. const routes: Array<RouteRecordRaw> = [
  3. {
  4. path:'/listFirst',
  5. name:'listFirst',
  6. component:()=>import('../pages/transmitInfo/list-first'),
  7. children:[
  8. {
  9. path:'listFirstA',
  10. components:{
  11. default:()=>import('../components/listFirstA')
  12. }
  13. },
  14. {
  15. path:'listFirstB',
  16. components:{
  17. listFirstB1:()=>import('../components/listFirstB1'),
  18. listFirstB2:()=>import('../components/listFirstB2')
  19. }
  20. }
  21. ]
  22. }
  23. ]
  24. const router = createRouter({
  25. history: createWebHistory(),
  26. routes
  27. })
  28. export default router

对应Router-view 通过name 对应组件

  1. <div>
  2. <div>
  3. <router-link to='/listFirst/listFirstA'>goodsCount</router-link>
  4. <router-link
  5. style="margin-left:20px;"
  6. to='/listFirst/listFirstB'>
  7. listFirstB</router-link>
  8. <hr>
  9. <div>
  10. <router-view></router-view>
  11. <router-view name='listFirstB1'></router-view>
  12. <router-view name='listFirstB12'></router-view>
  13. </div>
  14. </div>
  15. </div>

参考小满Router(第六章-命名视图)_小满zs的博客-CSDN博客

第七章  重定向&别名

重定向 redirect

1.字符串形式配置,访问/ 重定向到 /user (地址栏显示/,内容为/user路由的内容)

  1. const routes: Array<RouteRecordRaw> = [
  2. {
  3. path:'/',
  4. component:()=> import('../components/root.vue'),
  5. redirect:'/user1',
  6. children:[
  7. {
  8. path:'/user1',
  9. components:{
  10. default:()=> import('../components/A.vue')
  11. }
  12. },
  13. {
  14. path:'/user2',
  15. components:{
  16. bbb:()=> import('../components/B.vue'),
  17. ccc:()=> import('../components/C.vue')
  18. }
  19. }
  20. ]
  21. }
  22. ]

2.对象形式配置

  1. const routes: Array<RouteRecordRaw> = [
  2. {
  3. path: '/',
  4. component: () => import('../components/root.vue'),
  5. redirect: { path: '/user1' },
  6. children: [
  7. {
  8. path: '/user1',
  9. components: {
  10. default: () => import('../components/A.vue')
  11. }
  12. },
  13. {
  14. path: '/user2',
  15. components: {
  16. bbb: () => import('../components/B.vue'),
  17. ccc: () => import('../components/C.vue')
  18. }
  19. }
  20. ]
  21. }
  22. ]

3.函数模式(可以传参)

  1. const routes: Array<RouteRecordRaw> = [
  2. {
  3. path: '/',
  4. component: () => import('../components/root.vue'),
  5. redirect: (to) => {
  6. return {
  7. path: '/user1',
  8. query: {
  9. id:1
  10. }
  11. }
  12. },
  13. children: [
  14. {
  15. path: '/user1',
  16. components: {
  17. default: () => import('../components/A.vue')
  18. }
  19. },
  20. {
  21. path: '/user2',
  22. components: {
  23. bbb: () => import('../components/B.vue'),
  24. ccc: () => import('../components/C.vue')
  25. }
  26. }
  27. ]
  28. }
  29. ]

别名 alias

将 path的属性值 '/ '别名为 '/root','/root2','/root3',意味着当用户访问 /root ,  /root2  ,  /root3'时,URL是  /root 或 /root2 或 /root3 ,但会被匹配为用户正在访问 /

  1. const routes: Array<RouteRecordRaw> = [
  2. {
  3. path: '/',
  4. component: () => import('../components/root.vue'),
  5. alias:["/root","/root2","/root3"],
  6. children: [
  7. {
  8. path: 'user1',
  9. components: {
  10. default: () => import('../components/A.vue')
  11. }
  12. },
  13. {
  14. path: 'user2',
  15. components: {
  16. bbb: () => import('../components/B.vue'),
  17. ccc: () => import('../components/C.vue')
  18. }
  19. }
  20. ]
  21. }
  22. ]

参考 小满Router(第七章-重定向-别名)_小满zs的博客-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/379227
推荐阅读