59 Vue 路由 vue-router

Vue 路由 vue-router

1 Vue路由简介

1.vue-router 的理解

vue 的一个插件库,专门用来实现 SPA(单页面) 应用

2.对 SPA 应用的理解

  1. 单页 Web 应用(single page web application,SPA)。
  2. 整个应用只有一个完整的页面
  3. 点击页面中的导航链接不会刷新页面,只会做页面的局部更新
  4. 数据需要通过 ajax 请求获取。

3.路由的理解

  1. 什么是路由?
    1. 一个路由就是一组映射关系(key - value)
    2. key 为路径, value 可能是 function 或 component
  2. 路由分类
    1. 后端路由:
      1. 理解:value 是 function, 用于处理客户端提交的请求。
      2. 工作过程:服务器接收到一个请求时, 根据请求路径找到匹配的函来处理请求, 返回响应数据。
    2. 前端路由:
      1. 理解:value 是 component,用于展示页面内容。
      2. 工作过程:当浏览器的路径改变时, 对应的组件就会显

2 路由使用

路由

  1. 理解: 一个路由(route)就是一组映射关系(key - value),多个路由需要路由器(router)进行管理。
  2. 前端路由: key是路径,value是组件。

1.基本使用

  1. 安装vue-router,命令: npm i vue-router

  2. 应用插件: vue.use(VueRouter)

  3. 编写router配置项:

    import VueRouter from 'vue-router'
    import About from '../ components /About'
    import Home from '../ components /Home'
    
    export default new VueRouter({
        routes:[
            {
            	path:'/about', 
                component:About
            },
            {
            	path:'/home', 
                component:Home
            }
        ]
    })
    
    
  4. main引入并使用router

    ...
    import VueRouter from 'vue-router';
    import router from './router';
    Vue.use(VueRouter);
    
    new Vue({
        router,
        render: h => h(App),
    }).$mount('#app');
    
  5. 实现切换(active-class可配置高亮样式)

    <router-link active-class="active" to="/about">About</router-link>
    
  6. 指定展示位置

    <router-view></ router-view>
    

2.注意事项:

  1. 路由组件通常存放在pages文件夹,一般组件通常存放在 components文件夹。
  2. 通过切换,“隐藏"了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
  3. 每个组件都有自己的$route属性,里面存储着自己的路由信息。
  4. 整个应用只有一个router,可以通过组件的$router属性获取到。
// 同一router-view,当下一个路由组件创建时,前面的路由组件默认将会被销毁;
// 使用vue-router 会多出$route 和 $router
//  - $route: 每个组件都不同
//  - $router: 每个组件都相同,且一个应用只有一个

Home is mounted
Home is destroying
About is mounted
About is destroying
Home is mounted

>window.Aboutroute === window.Homeroute
false
>window.Aboutrouter === window.Homerouter
true

3 Vue嵌套(多级)路由

路由(多级)嵌套:

  • children: list -> path不带“/”,

  • : 带上父级

  1. 配置路由规则,使用children配置项:

    import VueRouter from 'vue-router';
    import Home from '../pages/Home';
    import About from '../pages/About';
    import New from '../pages/New';
    import Message from '../pages/Message';
    
    export default new VueRouter({
        routes: [
            {
                path: '/home',
                component: Home,
                children: [
                    {
                        path: 'new',
                        component: New,
                    },
                    {
                        path: 'message',
                        component: Message,
                    }
                ],
            },
            {
                path: '/about',
                component: About,
            }
        ],
    });
    
  2. 跳转(要写完整路径):

    <li><router-link to="/home/new">News</router-link></li>
    <li><router-link to="/home/message">Message</router-link></li>
    

4 路由query参数使用

query参数使用

  • $route.query

  • 使用方式:

    • 字符串写法

      <li v-for=" m in message" :key="m.id">
      	<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{ m.title }}</router-link>
      </li>
      
    • 对象写法

      li v-for=" m in message" :key="m.id">
          <router-link 
              :to="{
              	path:'/home/message/detail',
              	query:{
              		id:m.id,
              		title:m.title,
              	}
              }"
          >
          {{ m.title }}
          </router-link>
      </li>
      

5 命名路由

  1. 作用:可以简化路由的跳转。

  2. 如何使用

    1. 给路由命名:

      import VueRouter from 'vue-router';
      import Home from '../pages/Home';
      import About from '../pages/About';
      import New from '../pages/New';
      import Message from '../pages/Message';
      import Detail from '../pages/Detail';
      
      export default new VueRouter({
          routes: [
              {
                  path: '/home',
                  component: Home,
                  children: [
                      {
                          name: 'new',
                          path: 'new',
                          component: New,
                      },
                      {
                          name: 'message',
                          path: 'message',
                          component: Message,
                          children: [
                              {
                                  name: 'detail',
                                  path: 'detail',
                                  component: Detail,
                              }
                          ]
                      }
                  ],
              },
              {
                  path: '/about',
                  component: About,
              }
          ],
      });
      
    2. 简化路由跳转(路由过长)

      <!-- 原 -->
      <router-link :to="{path:'/home/message/detail'}"></router-link>
      <!-- 现 -->
      <router-link :to="{name:'detail'}"></router-link>
      

6 路由的params参数

特别注意: 路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!

  1. 配置路由,声明接收params参数

    import VueRouter from 'vue-router';
    import Home from '../pages/Home';
    import New from '../pages/New';
    import Message from '../pages/Message';
    import Detail from '../pages/Detail';
    
    export default new VueRouter({
        routes: [
            {
                path: '/home',
                component: Home,
                children: [
                    {
                        name: 'new',
                        path: 'new',
                        component: New,
                    },
                    {
                        name: 'message',
                        path: 'message',
                        component: Message,
                        children: [
                            {
                                name: 'detail',                 // 必须有name
                                path: 'detail/:id/:title',      // params占位
                                component: Detail,
                            }
                        ]
                    }
                ],
            },
        ],
    });
    
  2. 传递参数

    <ul>
        <li v-for=" m in message" :key="m.id">
            <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{ m.title }}</router-link>
        </li>
        <hr/>
        <router-view></router-view>
    </ul>
    
  3. 接收参教:

    {{$route.params.id}}
    {{$route.params.title}}
    

7 路由的props配置

作用: 让路由组件更方便的收到参数

  • 对象写法:固定数据
  • 布尔值写法:params数据
  • 函数写法:所有传递
import VueRouter from 'vue-router';
import Home from '../pages/Home';
import New from '../pages/New';
import Message from '../pages/Message';
import Detail from '../pages/Detail';

export default new VueRouter({
    routes: [
        {
            path: '/home',
            component: Home,
            children: [
                {
                    name: 'new',
                    path: 'new',
                    component: New,
                },
                {
                    name: 'message',
                    path: 'message',
                    component: Message,
                    children: [
                        {
                            name: 'detail',                 // 必须有name
                            path: 'detail/:id/:title',      // params占位
                            component: Detail,
                            // props: { 'a': 666, 'b': 'detail' }  // 对象写法,传递死数据
                            // props: true,                     // 布尔值写法,只对params生效
                            props($route) {                     // 函数式写法, 对route下的所有生效,函数默认给我们$route
                                return {
                                    id: $route.params.id,
                                    title: $route.params.title
                                }
                            }
                        }
                    ]
                }
            ],
        },
    ],
});

// 哪个需要接收数据就在那格里面写

8 <router-link>的replace属性

  1. 作用: 控制路由跳转时操作浏览器历史记录的模式
  2. 浏览器的历史记录有两种写入方式:
    1. 分别为pushreplacepush是追加历史记录,replace是替换当前记录。路由跳转时候, 默认为 push.
  3. 如何开启replace模式: <router-link replace ....... >News</router-link>.

push压栈

image-20221005163618857

操作流程:

  1. 打开网址
  2. /about
  3. /home
  4. /home/news

指针移动:默认在栈的最顶部。

replace 替换

replace 属性添加在News和Message上.

image-20221005163809526

操作流程:

  1. 打开网址
  2. /about
  3. /home (删)
  4. /home/news(删)
  5. /home/message

指针移动:默认在栈的最顶部。

9 编程式路由导航

  1. 作用:不借助<router-link>实现路由跳转,让路由跳转更加灵活

  2. 具体编码:

    pushShowMessage(m){
        this.$router.push({     // 实现router-link,点击跳转(显示组件) 默认push 压栈
            name:'detail',
            query:{
                id:m.id,
                title:m.title,
            }
        })
    }
        
    replaceShowMessage(m){
        this.$router.replace({     // 实现router-link,点击跳转(显示组件)repalce 替换
            name:'detail',
            query:{
                id:m.id,
                title:m.title,
            }
        })
    }
    
    this.$router.forward() //前进
    this.$router.back()    //后退
    this.$router.go()      //可前进也可后退
    

10 缓存路由组件

  1. 作用: 让不展示的路由组件保持挂载,不被销毁。

  2. 具体编码:

    <!-- keep-alive 路由缓, include属性不写,默认全部,写include使用include组件缓存 -->
    <keep-alive include="New">
        <router-view></router-view>
    </keep-alive>
    
    <!-- 多个 -->
    <keep-alive :include="[New,Message]">
        <router-view></router-view>
    </keep-alive>
    
    • keep-alive
      • include=“组件名”

11 两个新的生命周期钩子

注意: 另一个生命周期钩子:$nextTick(): 1.当你修改完数据后,2.vue操作完dom之后,3.把真实dom放入页面之后,4.再调用$nextTick()

  1. 作用: 路由组件所独有的两个钩子,用于捕获路由组件的激活状态。

  2. 具体名字:

    1. activated路由组件被激活时触发。
    2. deactivated路由组件失活时触发。
activated(){
    this.timer = setInterval(() => {
        this.opacity -= 0.01;
        if (this.opacity <= 0) this.opacity = 1;
    }, 16);
}

deactivated(){
    clearInterval(this.timer)    
}

12 路由守卫(权限\配置)

  1. 作用:对路由进行权限控制

  2. 分类:全局守卫、独享守卫、组件内守卫

  3. 全局守卫:

    // 全局前置路由守卫(权限) 
    router.beforeEach((to, from, next) => {
        if (to.meta.isAuth) {
            alert('无权访问!')
        } else {
            next();
        }
    })
    
    // 全局后置路由守卫(配置) 
    router.afterEach((to, from) => {
        document.title = to.meta.title || 'Sverdr';
    })
    
    // $route.meta:路由元信息,用于程序员配置;
    
  4. 独享守卫:

    // 独享路由守卫,单个路由使用
    beforeEnter(to, from, next) {
        if (to.meta.isAuth) {
            alert('无权访问!')
        } else {
            next();
        }
    },
    
  5. 组件内守卫:

    //进入守卫:通过路由规则,进入该组件时被调用
    beforeRouteEnter(to,from,next){
    },
    //离开守卫:通过路由规则,离开该组件时被调用
    beforeRouteLeave(to,from,next){
    },
    

image-20221006161358670

13 路由器的两种工作模式

  1. 对于一个url来说,什么是hash值?——#及其后面的内容就是hash值。

  2. hash值不会包含在HTTP请求中,即:hash值不会带给服务器。

  3. hash模式:

    1. 地址中永远带着#号,不美观。
    2. 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。
    3. 兼容性较好。
  4. history模式:

    1. 地址干净,美观。
    2. 兼容性和hash模式相比略差。
    3. 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。
posted @ 2022-10-05 13:31  Redskaber  阅读(38)  评论(0)    收藏  举报