import Vue from 'vue' import Router from 'vue-router' // @绝对路径 检索到 ...src/ // 如果Router当做局部模块使用一定要Vue.use(Router) // 以后在组件中,可以通过this.$router 获取Router实例化对象 // 路由信息对象 this.$routes 获取路由配置信息 import Home from '@/components/Home/Home' import Course from '@/components/Course/Course' import LightCourse from '@/components/LightCourse/LightCourse' import Micro from '@/components/Micro/Micro' Vue.use(Router) // 配置路由规则 export default new Router({ linkActiveClass: 'is-active', routes: [ { path: 'https://www.jb51.net/', redirect: '/home' // 访问/,直接跳转到/home路径 }, ...... { path: '/micro', name: 'Micro', component: Micro } ] })
(2)在LuffyHeader.vue中配置路由active样式
<template> ......省略 </template> <script> ......省略 </script> <style lang="css" scoped> .nav-center ul li a.is-active{ color: #4a4a4a; border-bottom: 4px solid #ffc210; } </style>
(3)显示效果
5、hash模式切换为 history 模式
vue-router 默认 hash 模式——使用URL的hash来模拟一个完整的URL,于是当URL改变时,页面不会重新加载。比如#/index,hash值为#/index。hash模式的特点在于hash出现在url中,但是不会被包括在HTTP请求中,对后端没有影响,不会重新加载页面。
如果不想要这种显示比较丑的hash,可以用路由的 history模式,这种模式充分利用 history.pushState API来完成URL跳转而无需重新加载页面。
(1)路由修改为history模式
修改 src/router/index.js 文件如下所示:
import Vue from 'vue' import Router from 'vue-router' // @绝对路径 检索到 ...src/ // 如果Router当做局部模块使用一定要Vue.use(Router) // 以后在组件中,可以通过this.$router 获取Router实例化对象 // 路由信息对象 this.$routes 获取路由配置信息 import Home from '@/components/Home/Home' import Course from '@/components/Course/Course' import LightCourse from '@/components/LightCourse/LightCourse' import Micro from '@/components/Micro/Micro' Vue.use(Router) // 配置路由规则 export default new Router({ linkActiveClass: 'is-active', mode: 'history', // 改为history模式 routes: [ { path: 'https://www.jb51.net/', redirect: '/home' // 访问/,直接跳转到/home路径 }, ..... ] })
使用history模式时,url就像正常url,例如,这样比较美观。
显示效果如下所示:
(2)后端配置
但是要用好这种模式,需要后台配置支持。vue的应用是单页客户端应用,如果后台没有正确的配置,用户在浏览器访问 就会返回404,这样就不好了。
因此要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是app依赖的页面。