首先官方文档: https://router.vuejs.org/zh/
Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。
export default new Router({ mode: ‘history‘, //路由模式,取值为history与hash base: ‘/‘, //打包路径,默认为/,可以修改 routes: [ { path: string, //路径 ccomponent: Component; //页面组件 name: string; // 命名路由-路由名称 components: { [name: string]: Component }; // 命名视图组件 redirect: string | Location | Function; // 重定向 props: boolean | string | Function; // 路由组件传递参数 alias: string | Array<string>; // 路由别名 children: Array<RouteConfig>; // 嵌套子路由 beforeEnter?: (to: Route, from: Route, next: Function) => void; // 路由单独钩子 meta: any; // 自定义标签属性,比如:是否需要登录 icon: any; // 图标 // 2.6.0+ caseSensitive: boolean; // 匹配规则是否大小写敏感?(默认值:false) pathToRegexpOptions: Object; // 编译正则的选项 } ] })
router-link标签跳转
//在html标签内使用router-link跳转,相应于超链接a标签
//to:导航路径
<p><router-link to="/">首页</router-link> <router-link to="/hello">hello</router-link> </p>
编程式导航
this.$router.push(‘/xxx‘)
<button @click="goHome">回到首页</button>
export default { name: ‘app‘, methods: { goHome(){ this.$router.push(‘/home‘); } } }
其他常用方法
// 后退一步记录,等同于 history.back() this.$router.go(-1) // 在浏览器记录中前进一步,等同于 history.forward() this.$router.go(1)
采用在children后跟路由数组来实现,数组里和其他配置路由基本相同,需要配置path和component,然后在相应部分添加<router-view/>来展现子页面信息,相当于嵌入iframe.
<!-- 添加子路由导航 --> <p> <router-link to="/home">首页</router-link> | <router-link to="/home/one">-子页面1</router-link> | <router-link to="/home/two">-子页面2</router-link> </p> <!-- 子页面展示部分 --> <router-view/>
export default new Router({ routes: [ { path: ‘/‘, // 默认页面重定向到主页 redirect: ‘/home‘ }, { path: ‘/home‘, // 主页路由 name: ‘Home‘, component: Home, children:[ // 嵌套子路由 { path:‘one‘, // 子页面1 component:One }, { path:‘two‘, // 子页面2 component:Two }, ] } ] })
<router-link :to="{name: ‘one‘, params:{username:‘test123‘}}">子页面1</router-link>
<h2>{{this.$route.params.username}}</h2>
//路由配置 { path:‘/home/two/:id/:name‘, // 子页面2 component:Two }, // 组件接受值 <p>ID:{{ $route.params.id}}</p> <p>名称:{{ $route.params.name}}</p> // router-link <router-link to="/home/two/1/张三">子页面2</router-link>
// router
{
path:‘/home/three‘, // 子页面3
name: ‘three‘,
component:Three
}
// template <button @click="toThreePage">页面3-params传参</button> // script methods: { toThreePage() { this.$router.push({name: ‘three‘, params: {id: 1, name: ‘zhangsan‘}}) } } // from template(three) <p>ID:{{ $route.params.id}}</p> <p>名称:{{ $route.params.name}}</p> //动态路由使用params传递参数,在this.$router.push() 方法中path不能和params一起使用,否则params将无效。需要用name来指定页面。
//以上方式参数不会显示到浏览器的地址栏中,如果刷新一次页面,就获取不到参数了,改进方式将第一部中的代码改成如下:
{
path:‘/home/three/:id/:name‘, // 子页面3
name: ‘three‘,
component:Three
}
//router { path:‘/home/three‘, // 子页面3 name: ‘three‘, component:Three } // template <button @click="toThreePage">页面3-params传参</button> // script methods: { toThreePage() { this.$router.push({path: ‘/home/three‘, query: {id: 24, name: ‘banzhuan‘}}) } } // from template(three) <p>ID:{{ $route.query.id}}</p> <p>名称:{{ $route.query.name}}</p> // 动态路由使用query传递参数,会显示到浏览器地址栏中,以上链接为 /home/three?id=24&name=banzhuan
命名路由
//给一个路由命一个唯一的名称,然后跳转调用这个名称即可 { path: ‘one‘, // 子页面1 name: ‘one‘, // 路由名称-命名路由 component: One // 页面组件 } // template跳转调用 <router-link :to="{name: ‘one‘}">子页面1</router-link> // router.push函数跳转调用 router.push({ name: ‘one‘}})
命名视图
//在同一个页面展示多个视图,如果不用嵌套,只能采用命名视图来实现 //Router.js // 创建页面组件 const Header = { template: ‘<div>Header</div>‘ } const Left = { template: ‘<div>Left</div>‘ } const Right = { template: ‘<div>Right</div>‘ } Vue.use(Router) export default new Router({ routes: [ { path: ‘/‘, // 主页路由 components: { default: Header, a: Left, b: Right } } ] }) //template xxx.vue <template> <div id="app"> <router-view /> <router-view name="a" class="left" /> <router-view name="b" class="right" /> </div> </template>
重定向
export default new Router({ routes: [ { path: ‘/‘, // 默认页面重定向到主页 redirect: ‘/home‘ // 重定向 不带参 }, { path: ‘/home‘, // 主页路由 component: Home, children:[ // 嵌套子路由 { path:‘/home/two/:id/:name‘, // 子页面2 component:Two }, { path:‘/home/three/:id/:name‘, // 子页面3 name: ‘three‘, // 路由名称-命名路由 redirect: ‘/home/two/:id/:name‘ // 重定向-传递参数 }, ] } ] })
<router-link to="/">首页</router-link> | <router-link to="/home/two/1/lisi">子页面2</router-link> | <router-link :to="{name: ‘three‘, params: {id: 24, name: ‘banzhuan‘}}">子页面3</router-link>
别名
{ path:‘/one‘, // 子页面1 component:One, alias: ‘/oneother‘ } <router-link to="/oneother">子页面1</router-link> // redirect和alias的区别 // redirect:直接改变了url的值,把url变成了真实的path路径。 // alias:url路径没有别改变,这种更友好,让用户知道自己访问的路径,只是改变了<router-view>中的内容。 // 别名请不要用在path为’/’中,如下代码的别名是不起作用的。 { path: ‘/‘, component: Hello, alias:‘/home‘ }
<transition name="fade" mode="out-in"> <router-view /> </transition> //四个类名与transition的name属性有关,比如name="fade" /*页面切换动画*/ /*进入过渡的结束状态,元素被插入时就生效,在过渡过程完成后移除*/ .fade-enter-active { transition: opacity .5s; } /*进入过渡的开始状态,元素被插入时生效,只应用一帧后立刻删除*/ .fade-enter { opacity: 0; } /*离开过渡的开始状态,元素被删除时触发,只应用一帧后立刻删除*/ .fade-leave { opacity: 1; } /*离开过渡的结束状态,元素被删除时生效,离开过渡完成后被删除*/ .fade-leave-active { opacity:0; transition: opacity .5s; }
export default new Router({ mode: ‘history‘, //mode模式 routes: [...] })
mode取值说明:
(1)histroy:URL就像正常的 url,示例:http://localhost:8080/home
(2)hash:默认值,会多一个“#”,示例:http://localhost:8080/#/home
//如果访问的路由不存在,或者用户输入错误时,会有一个404友好的提示页面,配置如下: { path: ‘*‘, component: () => import(‘@/components/404‘) }
全局钩子函数
// 定义路由配置 const router = new VueRouter({ ... }) // 全局路由拦截-进入页面前执行 router.beforeEach((to, from, next) => { // 这里可以加入全局登陆判断 // 继续执行 next(); }); //在 2.5.0+ 你可以用 router.beforeResolve 注册一个全局守卫。这和 router.beforeEach 类似,区别是在导航被确认之前,同时在所有组件内守卫和异步路由组件被解析之后,解析守卫就被调用。 router.beforeResolve((to, from, next) => { if (true) { console.log("beforeResolve 验证通过"); next(); } else { console.log("beforeResolve 验证失败"); } }); // 全局后置钩子-常用于结束动画等 router.afterEach(() => { //不接受next }); export default router; //to: Route : 即将要进入的目标 [路由对象] //from: Route : 当前导航正要离开的路由 //next: Function : 继续执行函数 //next():继续执行 //next(false):中断当前的导航。 //next(‘/‘) 或 next({ path: ‘/‘ }):跳转新页面,常用于登陆失效跳转登陆
路由独享钩子函数
//在路由配置中单独加入钩子 { path:‘/home/one‘, // 子页面1 component: One, // 路由内钩子 beforeEnter: (to, from, next) => { console.log(‘进入前执行‘); next(); } }
组件内的钩子函数
//在路由组件内定义钩子函数: //beforeRouteEnter:进入页面前调用 //beforeRouteUpdate (2.2 新增):页面路由改变时调用,一般需要带参数 //beforeRouteLeave:离开页面调用 <script> export default { name: ‘Two‘, data () { return { msg: ‘Hi, I am Two Page!‘ } }, // 进入页面前调用 beforeRouteEnter(to, from, next) { console.log(‘进入enter路由钩子‘) next() }, // 离开页面调用 beforeRouteLeave(to,from, next){ console.log(‘进入leave路由钩子‘) next() }, // 页面路由改变时调用 beforeRouteUpdate(to, from, next) { console.log(‘进入update路由钩子‘) console.log(to.params.id) next() } } </script>
//大项目中,为了提高初始化页面的效率,路由一般使用懒加载模式,一共三种实现方式。 component: (resolve) => require([‘@/components/One‘], resolve) component: () => import(‘@/components/Two‘) components: r => require.ensure([], () => r(require(‘@/components/Three‘)), ‘group-home‘)
// 第三种中,’group-home’是把组件按组分块打包, 可以将多个组件放入这个组中,在打包的时候Webpack会将相同 chunk 下的所有异步模块打包到一个异步块里面。
原文:https://www.cnblogs.com/zhangxiaoqiong/p/13684488.html