1、什么是前端路由html
提起路由,平时咱们最熟悉的是路由器,根据数据包的目的ip进行正确的转发。前端路由能够类比路由器,根据url显示不一样的页面。因为ajax的出现,可让前端实现不用刷新页面也能够获取新的内容,所以有两种基于ajax的前端路由实现方式。前端
2、前端路由实现方式vue
一、history方式html5
html5 history的api中提供了history.pushState()和history.replaceState()以及一个事件window.onpopstate()ajax
history.pushState(stateObj, title, url)vue-router
这个方法用于建立一条新的历史记录并指向传入的url,参数表stateObj用于传入当前的状态对象,title通常会被忽略,能够传入一个空字符串,url是要跳转的连接(通常是相对路径)segmentfault
history.replaceState(stateObj, title, url)api
它基本和pushState差很少,惟一不一样的地方在于它不会建立新的历史记录,只是会把当前的历史记录的url替换掉浏览器
window.onpopstate()框架
它的触发条件十分苛刻,基本上能够用于在用上面两个方法建立的历史记录之间导航(前进或后退),同时,前面2个方法所设置的状态对象(第1个参数),也会在这个时候经过事件的event.state返还回来
history方式是用ajax请求替代<a>的跳转,同时利用history方法替换url,新的url必须和前一个url同源,不然会报错,因此无需刷新页面;可是它的缺点是html5的history API可能会有些浏览器不兼容
二、hash方式
咱们常常在 url 中看到 #,这个 # 有两种状况,一个是咱们所谓的锚点,好比典型的回到顶部按钮原理、Github 上各个标题之间的跳转等,路由里的 # 不叫锚点,咱们称之为 hash,大型框架的路由系统大多都是哈希实现的(由于hash的兼容性较好)。它主要依靠window.onhashchange监听hash发生改变的时候,而后经过window.location处理hashchange事件,这种状况下页面不会从新渲染,能够经过注册ajax请求完成页面的刷新
3、vue-router
vue官方支持的router,api:https://router.vuejs.org/
一、命名路由
const router = new VueRouter({ routes: [ { path: '/user/:userId', name: 'user', component: User } ] })
二、嵌套路由
onst router = new VueRouter({ routes: [ { path: '/user/:id', component: User, children: [ { // UserProfile will be rendered inside User's <router-view> // when /user/:id/profile is matched path: 'profile', component: UserProfile }, { // UserPosts will be rendered inside User's <router-view> // when /user/:id/posts is matched path: 'posts', component: UserPosts } ] } ] })
三、历史模式
vue-router提供了一个history模式,在使用hash方式实现路由的功能的状况下,url中不会显示#
const router = new VueRouter({ mode: 'history', routes: [...] })