router进阶

建议直接查看官方文档:

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

```




复制代码
相关文章
相关标签/搜索