我爱编程

vue-router总结

2018-04-16  本文已影响38人  取个帅气的名字真好

1、通过 :to 传参

//需要传的参数在params中
<router-link :to="{name:'A',params:{usename:'李四',age:'24'}}">A</router-link>
//接收参数
{{$route.params.usename}}  //李四

{{$route.params.age}}  // 24

2、通过URL传参

router/index.js

{
// 格式:/路径/:id
// (\\w+):匹配正则
  path: '/Hi/:id(\\w+)/:name', 
  name: 'Hi',
  component:Hi //组件
},

App.vue

// 把12345和王五传过去
<router-link to="/Hi/12345/王五">Hi</router-link>

Hi.vue

//接收
 <p>{{$route.params.id}}</p>
 <p>{{$route.params.name}}</p>
效果

重定向 redirect

当用户访问 /a时,URL 将会被替换成 /b,然后匹配路由为 /b

//index.js
  {
    path: '/goHome', //路径
    name: 'goHome',
    redirect:'/' //  重定向回到的路径 
  },
//APP.vue
 <router-link to="/goHome">回到首页</router-link>

重定向并返回参数

//index.js
{
  path: '/goHi/:content1/:content2', //路径
  name: 'goHi',
  redirect: '/Hi/:content1/:content2' //重定向传参
},
//App.vue
 <router-link to="/goHi/456/重定向返回的参数">goHi</router-link>
//Hi.vue
<p>{{$route.params.content1}}</p>
<p>{{$route.params.content2}}</p>
重定向并传参

别名 alias

/Alias1 的别名是 /Alias2,意味着,当用户访问 /Alias2 时,URL 会保持为 /Alias2,但是路由匹配则为 /Alias1,就像用户访问 /Alias1 一样。

//index.js

{
  path: '/Alias1', 
  name: 'Alias1',
  component:Alias1,
  alias: '/Alias2'  // 关键 
},

//App.vue

<router-link to="/Alias1">Alias1</router-link>
<router-link to="/Alias2">Alias2</router-link>
//Alias1.vue

<template>
  <div>
    <hr>
        <h1> 这里是【别名】alias1</h1>
  </div>
</template>
别名效果

路由过渡动画

1、 组件过渡过程中,会有四个CSS类名进行切换,这四个类名与上面transition的name属性有关,比如name="bbb",会有如下四个CSS类名:
2、过渡模式mode
//APP.vue
<transition name="bbb" mode="out-in"> 
  <router-view/>
</transition>

// css

<style>
  .bbb-enter {
    opacity: 0;
  }
  .bbb-enter-active {
    transition: opacity 0.5s;
  }
  .bbb-leave {
    opacity: 1;
  }
  .bbb-leave-active {
    opacity: 0;
    transition: opacity 0.5s;
  }
</style>

更多请看vue文档

路由过渡动画

mode

可选值:

注意:并非transition中的mode

//index.js

Vue.use(Router)
export default new Router({

  mode: 'history',

  routes: [...]
})

hash和history最根本的区别是:是否有 #

history hash

404页面

当用户输入URL错误时,我们希望有个404页面跳出来让用户知道自己输入错误了。

//index.js

//引入404页面
import Error from '@/components/Error'

// 404页面路由配置   
{
  path: '*',  // 重点
  name:'Error',
  component: Error,
}

//Error.vue
<template>
  <div>
    <hr>
    <h1> 404 </h1>
    <h2>老铁页面不存在</h2>
  </div>
</template>
404页面

路由中的钩子函数


1、beforeEnter:全局前置守卫

{
  path: '/Hi/:id(\\w+)/:name', //路径
  name: 'Hi',
  component: Hi, //组件
  beforeEnter: (to, from, next) => {
    console.log(to)
    console.log(from)
    // true:跳转   false:不跳转  {path:'/'}: 跳转到根目录
    next({path:'/'}) 
  }
},

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

from:当前导航正要离开的路由
next() :进行管道中的下一个钩子。
next(false) :停止跳转。
next(true): 正常跳转
next({path:'/'}) :跳转到某个地址。如:首页

参考

上一篇 下一篇

猜你喜欢

热点阅读