vue-router详解

vue-router

1. vue-router 是什么

SPA的路径管理器 路由模块的本质就是 建立起url和页面之间的映射关系

2. vue-router 实现原理

​ **单页面应用 核心之一:更新视图而不重新请求页面 **

提供了两种方式:Hash History 根据 mode 参数来决定采用哪种方式

  1. Hash
    • 默认hash模式 使用URL的hash来模拟一个完整的URL 当URL 改变时 页面不会重新加载
    • Hash模式 通过锚点值的改变 根据不同的值 渲染指定DOM位置的不同数据
  2. History
    • 需要后台配置支持 如果 URL 匹配不到任何静态资源 则应该返回同一个index.html 页面
  3. 使用路由模式来实现页面跳转的方式
    • 直接修改地址栏
    • this.$router.push('路由地址')

3. 使用方式

  1. **下载 **

    npm i vue-router -S
    
  2. 引入

    // main.js
    import VueRouter from 'vue-router';
    // 安装插件
    Vue.ues(VueRouter)
    
  3. 创建 路由对象 并配置路由规则

    let router = new VueRouter({
        routes:[
            {path:'/',component:组件}
        ]
    })
    
  4. 将 路由对象传递给Vue的实例 options中加入 router:router

  5. app.vue 中 使用

    具体代码:

    
    //main.js文件中引入
    import Vue from 'vue';
    import VueRouter from 'vue-router';
    //主体
    import App from './components/app.vue';
    import Home from './components/home.vue'
    //安装插件
    Vue.use(VueRouter); //挂载属性
    //创建路由对象并配置路由规则
    let router = new VueRouter({
        routes: [
            //一个个对象
            { path: '/home', component: Home }
        ]
    });
    //new Vue 启动
    new Vue({
        el: '#app',
        //让vue知道我们的路由规则
        router: router, //可以简写router
        render: c => c(App),
    })
    
    
    //app.vue中
    
    
    
  6. 路由拆分

    // 建立 /src/router/index.js
    import Vue from 'vue'
    import VueRouter from 'vue-router'
    import Home from '../views/Home.vue'
    // 注入插件
    Vue.use(VueRouter)
    // 定义路由
    const routes = [
        // 添加映射关系
      {
        // 默认首页
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: Home
      },
    ]
    // 创建router实例
    const router = new VueRouter({
      mode: 'history || hash',
      routes
    })
    // 导出router实例
    export default router
    
    
    // main.js 修改
    import router from './router';
    new Vue({
        router:router, //可以简写router
    })
    
  7. 细节处理

    • 默认路径

      //默认首页
      path: '/',
      redirect: '/home'
      // 配置解析:我们在routes中又配置了一个映射。 
      // path配置的是根路径: /,redirect是重定向, 将根路径重定向到/home的路径下
      
      // 与 alias的 区别
      // redirect:仔细观察URL,redirect是直接改变了url的值,把url变成了真实的path路径。
      // alias:URL路径没有别改变,这种情况更友好,让用户知道自己访问的路径,只是改变了中的内容
      // alias 在 path 为 '/' 中 不起作用
      
    • 路由模式

      const router = new VueRouter({
        mode: 'history', //history模式
        routes
      })
      
    • router-link

      • to:跳转到指定的路径
      • tag:指定router-link 渲染成什么标签组件 默认是
      • replace:不会留下history记录
      • active-class:当前显示路由 高亮
    • 修改linkkActiveClass

      // class 具体的名称可以通过router实例的属性进行修改
      const router = new VueRouter({
        mode: 'history',
        routes,
        linkActiveClass: 'active' //修改类名称
      })
      
    • 代码跳转

      
       
      
      

4. 核心要点

  1. 参数传递

    • params类型

      格式:/router/id

      传递方式:在path后面跟上对应的值

      传递后形成的路径:/router/123

      【ps】提供path后 params 会被忽略

      const userId = 123
      router.push({ name: 'user', params: { userId }}) // -> /user/123
      router.push({ path: `/user/${userId}` }) // -> /user/123
      // 这里的 params 不生效
      router.push({ path: '/user', params: { userId }}) // -> /user
      
    • query类型

      格式:/router

      传递方式:对象中使用query的key作为传递方式

      传递后形成的路径:/router?id=123

    • 方式

      
      
      
      // 通过代码进行参数传递
      linktoProfile() {
          this.$router.push({
              path: '/profile/' + abc,
              query: {
                  name: 'wugongzi',
                  age: 18
              }
          })
      }
      
    • name 传递参数

      路由文件中 配置name属性

      routes:[
          {
              path:'/',
              name:'Hello',
              component:Hello
          }
      ]
      

      模板中用 $router.name 的形式来接收

      {{ $router.name }}

      通过 标签中的to传参

      东西里
      

      在router-link中 可以用路由的名字来链接到一个路由

      $router.params.username 来接收


    【PS】组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性

    // 使用props将组件和路由解耦
    const router = new VueRouter({
      routes: [
        { path: '/user/:id', component: User, props: true },
     
        // 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
        {
          path: '/user/:id',
          components: { default: User, sidebar: Sidebar },
          props: { default: true, sidebar: false }
        }
      ]
    })
    
    

    props模式

    1. 布尔模式 值 为 true route.params 将会被设置为组件属性
      1. 对象模式 值 为 对象 按原样设置为组件属性 当 props 是静态的时候有用
      2. 函数模式 值 为 函数 将参数转换成另一种类型 将 静态值 与 基于路由的值结合
  2. 获取参数

    通过 $route 对象获取

    • $route 和 $router 的区别
      • $router 为 VueRouter实例 想要导航到不同的URL 则使用 $router.push 方法
      • $route 为 当前router跳转对象 里面可以获取 name path query params
  3. 响应路由变化

    // 复用组件时,想对路由参数的变化作出响应的话:
    const User = {
      template: '...',
      watch: {
        '$route' (to, from) {
          // 对路由变化作出响应...
        }
      }
    }
    
    // 如果目的地和当前路由相同,只有参数发生了改变 使用 beforeRouteUpdate来响应这个变化 (比如抓取用户信息)
    const User = {
      template: '...',
      beforeRouteUpdate (to, from, next) {
        // react to route changes...
        // don't forget to call next()
      }
    }
    
    
  4. 单页面 多路由区域操作

    
    
    
    // 需要在路由里配置这三个区域,配置主要是在components字段里进行 
    routes: [
          {
            path: '/',
            name: 'HelloWorld',
            components: {default: HelloWorld,
              left:H1,//显示H1组件内容'I am H1 page,Welcome to H1'
              right:H2//显示H2组件内容'I am H2 page,Welcome to H2'
            }
          },
          {
            path: '/h1',
            name: 'H1',
            components: {default: HelloWorld,
              left:H2,//显示H2组件内容
              right:H1//显示H1组件内容
            }
          }
        ]
    
    
  5. 配置子路由

     routes: [
       {
         path: '/',
         name: 'HelloWorld',
         component: HelloWorld,
         children: [
            {path: '/h1', name: 'H1', component: H1},
           	{path: '/h2', name: 'H2', component: H2}
         ]
       }
     ]
    
  6. 跳转方式

    • router.push()
    • router.replace()
    • router.go(n) 在history记录中向前或向后退多少步

5. 路由中的钩子

  1. 全局路由守卫

    • 全局前置守卫

    • 全局后置守卫

      router.beforeEach((to,from,next)=>{
          console.log(to)  // 到哪个页面去
          console.log(from)  // 从哪个页面来
      	next()			// 一个回调函数
      })
      // next(false)  中断当前导航 如果浏览器的URL 改变了 那么URL会重置到from路由对应的地址
      // next('/')  next({path:'/'})  跳转到一个不同的地址  可以传递对象 设置 replace : true 之类的 以及任何在router-link 的to  prop  或者router.push 的选项  简而言之  对象可传参
      router.afterEach((to,from)=>{
          
      })
      
  2. 组件路由守卫

    • 到达组件时

      // 跟 methods:{} 同级使用  组件路由守卫 是 卸载每个单独的vue文件里的
      beforeRouteEnter(to,from,next){
          // 在路由进入之前 组件实例未渲染 无法获取this实例 只能通过vm来访问组件实例
          next(vm => {})
      }
      
    • 一个页面内 不同的数据刷新

      beforeRouteUpdate(to,from,next){
          // 同一页面 刷新不同数据时调用
      }
      
    • 离开组件时

      beforeRouteLeave(to,from,next){
          // 离开当前路由页面时调用
      }
      
  3. 路由独享守卫

    export default new VueRouter({
        routes: [
            {
                path: '/',
                name: 'home',
                component: 'Home',
                beforeEnter: (to, from, next) => {
                   // ...
                }
            }
        ]
    })
    

你可能感兴趣的:(Vue,vue.js,javascript,前端)