前端路由

一、什么是前端路由

提起路由,平时我们最熟悉的是路由器,根据数据包的目的ip进行正确的转发。前端路由可以类比路由器,根据url显示不同的页面。由于ajax的出现,可以让前端实现不用刷新页面也可以获取新的内容,因此有两种基于ajax的前端路由实现方式。

二、前端路由实现方式

1、history方式

html5 history的api中提供了history.pushState()和history.replaceState()以及一个事件window.onpopstate()

history.pushState(stateObj, title, url)

这个方法用于创建一条新的历史记录并指向传入的url,参数表stateObj用于传入当前的状态对象,title一般会被忽略,可以传入一个空字符串,url是要跳转的链接(一般是相对路径)

history.replaceState(stateObj, title, url)

它基本和pushState差不多,唯一不同的地方在于它不会创建新的历史记录,只是会把当前的历史记录的url替换掉

window.onpopstate()

它的触发条件十分苛刻,基本上可以用于在用上面两个方法创建的历史记录之间导航(前进或后退),同时,前面2个方法所设置的状态对象(第1个参数),也会在这个时候通过事件的event.state返还回来

history方式是用ajax请求替代<a>的跳转,同时利用history方法替换url,新的url必须和前一个url同源,否则会报错,所以无需刷新页面;但是它的缺点是html5的history API可能会有些浏览器不兼容

本部分参考

2、hash方式

我们经常在 url 中看到 #,这个 # 有两种情况,一个是我们所谓的锚点,比如典型的回到顶部按钮原理、Github 上各个标题之间的跳转等,路由里的 # 不叫锚点,我们称之为 hash,大型框架的路由系统大多都是哈希实现的(因为hash的兼容性较好)。它主要依靠window.onhashchange监听hash发生改变的时候,然后通过window.location处理hashchange事件,这种情况下页面不会重新渲染,可以通过注册ajax请求完成页面的刷新

本部分参考

三、vue-router

vue官方支持的router,api:https://router.vuejs.org/

1、命名路由

const router = new VueRouter({
  routes: [
    {
      path: '/user/:userId',
      name: 'user',
      component: User
    }
  ]
})

2、嵌套路由

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
        }
      ]
    }
  ]
})

3、历史模式

vue-router提供了一个history模式,在使用hash方式实现路由的功能的情况下,url中不会显示#

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

 

posted @ 2018-10-16 15:38  sue7  阅读(190)  评论(0编辑  收藏  举报