router进阶

本文详细介绍了 Vue Router 的核心功能,包括路由组件传参的三种方式:布尔模式、对象模式和函数模式,以及 html5History 模式的使用方法。深入探讨了导航守卫的应用场景,如登录验证和权限控制,并解析了路由元信息和路由切换动画的实现。

建议直接查看官方文档:

https://router.vuejs.org/zh/guide/advanced/meta.html


主要内容
- 路由组件传参
- html5 History 模式
- 导航守卫
- 路由元信息
- 过渡效果


### 路由组件传参

参数的获取,可以通过

```
this.$router.params.id 或者this.$router.query.id 
```
来获取;但是,有缺陷。就是页面组件,和路由进行了高度耦合。

为了解,组件高度复用,就要用到路由组件传参


#### 路由组件传参3种形式。


第一种:布尔模式。适用于,在动态路由匹配中,有动态路由参数的路由配置中。为了解耦,需要在组件页面,把传进来的参数以属性的方式进行解耦。


```
//router.js 中配置

{
    path:'/detail/:id',
    name:'detail',
    component:Detail,
    props:true//里面的参数,来控制使用把路由参数作为对象的属性
}

//vue 文件
<div>{{name}}</div>

<script>
export default{
    pros:{
        id:{
           type:[String,Number],
           default:0 //给一个默认参数
        }
    }
}

</script>
```
### 第二种方式,普通的  对象模式


```
//router.js
{
    path:'/self',
    name:'self',
    component:Self,
    props:{
        name:'李四'
    }
}





//vue.js
<div>{{name}}</div>

<script>

export default{
    props:{
        name:{
            type:String,
            default:'张三'
        }
    }
}

</script>
```
### 函数模式 
适合于在传入的属性中能够根据当前的路由,来做一些处理逻辑,来设置传入组件的属性值

```
//router.js
{
    path:'home',
    name:'home',
    component:Home,
    props:res=>({
        id:res.query.id
    })
}


//.vue 文件

{{id}}

<script>
export default {
    props:{
        id:{
            type:String,
            default:'123'
        }
    }
}

</script>
```

## html5 router的 mode  模式


vue-router 

```
router index.js

export default new Router({
    mode:'hash',
    routes
})
```

mode:hash / history


mode :模式,默认是(hash)哈希模式,在浏览器的url中,会有# 出现。
history: 利用的是history的api,做无刷新的页面跳转。
这种模式需要后端来进行配合。

后面写:为什么,后端如何实现



Apache 
```
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
```
nginx

```
location / {
  try_files $uri $uri/ /index.html;
}
```
node.js

```
const http = require('http')
const fs = require('fs')
const httpPort = 80

http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" file.')
    }

    res.writeHead(200, {
      'Content-Type': 'text/html; charset=utf-8'
    })

    res.end(content)
  })
}).listen(httpPort, () => {
  console.log('Server listening on: http://localhost:%s', httpPort)
})
```
可参考:https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90





使用history模式,没有# 号出现。

使用history 模式,所有匹配不到的静态资源,都需要指向一个通用的页面,在路由里面加配置,兼容处理这种模式带来的问题



```
{
    path:'*',
    component:404Error
}
```

这个指向,要定义到最后,因为这个json 文件是从上到下执行的。
如果先执行了上述的对象,那么都会报404Error了



### 导航守卫

功能是路由发生跳转,到导航结束的时间内,做逻辑处理

比如:登录,权限控制
例如:

```
/**
 * 当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。

每个守卫方法接收三个参数:

to: Route: 即将要进入的目标 路由对象

from: Route: 当前导航正要离开的路由

next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

next(): 进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

next(false): 中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。

确保要调用 next 方法,否则钩子就不会被 resolved。


 * 
 * 
 * 
 * 
 */


/* 全局守卫示例 */

/*
*router.beforeEach((to,from,next)=>{
    //业务代码
})







*/

// 添加路由守卫
/**
 * 判断是否有eleToken,用来判断是否登录了
 * 
 */


router.beforeEach((to, from, next) => {
  const isLogin = localStorage.eleToken ? true : false;
  /** 
   * 判断是不是从login,或者register 页面,如果是那么继续,
   * 如果不是,那么判断isLogin是否存在
   * 如果存在那么继续,如果不存在,那么跳转到login
   * 
  */
  if (to.path == "/login" || to.path == "/register") {
    next();
  } else {
    isLogin ? next() : next("/login");
  }
})
```

## 导航守卫

全局守卫
```
router.beforeEach((to, from, next) => {
  // ...
})
```
全局解析守卫(和全局守卫类似,区别在于导航被确认之前,同时在所有的组件内守卫和异步路由组件被解析之后,解析守卫就被调用)


```
router.beforeResolve((to, from, next) => {
  // ...
})
```
全局后置钩子

守卫不同的是,这些钩子不会接受 next 函数也不会改变导航本身
```
router.afterEach((to, from) => {
  // ...
})
```

路由独享的守卫

```
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})
```

组件内的守卫

```
const Foo = {
  template: `...`,
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate (to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave (to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }
}
```


### 完整的导航解析流程
```

导航被触发。
在失活的组件里调用离开守卫(beforeRouteLeave)。
调用全局的 beforeEach 守卫。
在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。
在路由配置里调用 beforeEnter。
解析异步路由组件。
在被激活的组件里调用 beforeRouteEnter。
调用全局的 beforeResolve 守卫 (2.5+)。
导航被确认。
调用全局的 afterEach 钩子。
触发 DOM 更新。
用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。
```



## 路由元信息

```
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})
```
## 路由切换动画

```
 <transition-group name="router">      <router-view key="default" />      <router-view key="tel"                   name="tel" />      <router-view key="email"                   name="email" />    </transition-group>


.router-enter  opacity 0.router-enter-active  transition 1s opacity ease.router-enter-to  opacity 1.router-leave  opacity 1.router-leave-active  transition 1s opacity ease.router-leave-to  opacity 0

```




复制代码


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值