SPA(单页应用):单页应用,只有一个完整的页面,加载时,不会加载整个页面。当路由发生变化时,监听路由的变化,不会请求页面,只会更新视图。路由描述了URL和UI的映射关系,即URL变化引起UI更新(无需刷新页面)。Vue生态中提供了VueRouter来实现单页面前端路由。VueRouter有两种常见的模式:Hash模式和History模式。哈希模式VueRouter默认为哈希模式。Hash是URL的哈希(#)和后面的部分。它通常用作在页面内导航的锚点。如果更改URL中的散列,浏览器将不会重新加载。hash(#)只是引导浏览器,不会包含在http请求中,所以页面不会重新加载,hash模式的原理是通过onhashchange事件监听URL的变化。History模式history模式是通过使用HTML5History新的pushState()和replaceState()方法以及popstate事件实现的。通过浏览器的前进和后退改变URL时会触发popstate事件;但是通过pushState/replaceState或标签更改URL不会触发popstate事件。pushState/replaceState除了之前的back,forward,go方法外,还提供了修改历史记录的功能。但是在修改的时候,虽然修改了url,但是并不会马上向服务器发送请求。当你使用history模式时,URL就像一个普通的url,例如http://localhost:8080/about,但是这种模式也需要后台配置支持。因为我们的应用是单页客户端应用,如果后台配置不正确,当用户在浏览器中直接访问http://localhost:8080/about时,会返回404。所以servery需要添加一个覆盖所有情况的候选资源:如果url没有匹配到任何静态资源,应该返回相同的index.html页面,也就是你的app依赖的页面。简易版VueRouter实现用法分析首先我们看一下VueRouter的用法安装VueRouter,importVueRouterfrom'vue-router',使用Vue.use(VueRouter)这样每个组件都可以有一个store实例importVueRouterfrom'vue-router'Vue.use(VueRouter)创建一个Router实例,router.js...constrouter=newVueRouter({routes})exportdefaultrouter在根组件上添加实例,main.jsimportrouterfrom'./router'newVue({router,render:h=>h(App)}).$mount('#app')添加路由视图,App.vuenavigation首页关于About2按照上面的用法,我们需要实现:实现VueRouter类和install方法。全局组件:router-view用于显示匹配的组件内容,router-link用于跳转。监控url变化:监听hashchange或popstate事件。创建一个响应式属性current,获取对应的组件,当它发生变化时显示。首先在根目录下创建路由器文件和其他文件:router|--index.js|--router-link.js|--router-view.js`--vue-router.jsVueRouter类及安装方法//router/vue-router.jsimportLinkfrom'./router-link'importViewfrom'./router-view'letVueclassVueRouter{constructor(options){this.$options=options//使用Vue提供的defineReactive响应当current改变时,依赖的组件会重新渲染Vue.util.defineReactive(this,'current','/')//监听url变化window.addEventListener('hashchange',this.onHashChange.bind(this))window.addEventListener('load',this.onHashChange.bind(this))//创建路由映射this.routeMap={}options.routes.forEach(route=>{this.routeMap[route.path]=route})}onHashChange(){this.current=window.location.hash.slice(1)}}VueRouter.install=function(_Vue){Vue=_VueVue.mixin({beforeCreate(){root//确保只有当实例被执行if(this.$options.router){Vue.prototype.$router=this.$options.router}}})Vue.component('router-link',Link)Vue.component('router-view',View)}exportdefaultVueRouterrouter-link组件//router/router-link.jsexportdefault{props:{to:{type:String,required:true}},render(h){returnh('a',{attrs:{href:#'+this.to}},this.$slots.default)//return{this.$slots.default}}}routor-view组件//router/router-view.jsexportdefault{render(h){//获取路径对应的组件const{routeMap,current}=this.$routerconstcomponent=routeMap[current].component||nullreturnh(component)}}实例化Router//router/index.jsimportVuefrom'vue'importVueRouterfrom'./vue-router'importHomefrom'../views/Home.vue'Vue.use(VueRouter)constroutes=[{路径:'/',名称:'主页',组件:主页},{路径:'/about',名称:'关于',组件:()=>导入(/*webpackChunkName:“关于”*/'../views/About.vue')},{路径:'/about2',名称:'About2',component:()=>import(/*webpackChunkName:"about2"*/'../views/About2.vue')}]constrouter=newVueRouter({routes})exportdefaultrouter