前端路由: hash & history 模式

1、 history 模式

history原理: 利用H5的 history中新增的兩個API pushState() 和 replaceState() 和一個事件onpopstatevue

pushState是往history對象裏添加一個新的歷史記錄,即壓棧。 replaceState 是替換history對象中的當前歷史。 這兩個api 接受三個參數:vue-router

history.pushState(
    {
        key: 'value'    // 狀態對象
    },
    'title',            // 標題
    'url'               // url
)
複製代碼

當點擊瀏覽器後退按鈕或js調用history.back都會觸發onpopstate事件編程

缺陷:

直接訪問二級頁面或者在頁面內刷新,會出現404錯誤後端

解決方法:

後端ngnix中配置重定向到首頁路由上api

2、hash模式

原理是監聽onhashchange()事件。僅 hash 符號以前的內容會被包含在請求中,如 www.abc.com,所以對於後端來講,即便沒有作到對路由的全覆蓋,也不會返回 404 錯誤。數組

3、[vue-router][1]

vue-router默認hash模式瀏覽器

3.1 訪問路由器

this.$router  // 訪問路由器
this.$route   // 訪問當前路由
複製代碼

3.2 動態路由匹配

const router = new VueRouter({
  routes: [
    // 動態路徑參數 以冒號開頭
    { path: '/user/:id', component: User }
  ]
})

const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
複製代碼

3.3 嵌套路由

要在嵌套的出口中渲染組件,須要在 VueRouter 的參數中使用 children 配置:bash

const User = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      <router-view></router-view>
    </div>
  `
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User,
      children: [
        {
          // 當 /user/:id/profile 匹配成功,
          // UserProfile 會被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
          // 當 /user/:id/posts 匹配成功
          // UserPosts 會被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]
})
複製代碼

3.4 編程式導航

router.push():向 history 棧添加一個新的記錄 router.replace():替換掉當前的 history 記錄。 router.go(n): 在 history 記錄中向前或者後退多少步 效仿window.history API,且在各種路由模式(history,hash)下表現一致post

// 字符串
router.push('home')

// 對象
router.push({ path: 'home' })

// 命名的路由(若是提供了 path,params 會被忽略)
router.push({ name: 'user', params: { userId: 123 }})

// 帶查詢參數,變成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
複製代碼

3.5 導航守衛

全局守衛

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // to: Route: 即將要進入的目標 路由對象
  // from: Route: 當前導航正要離開的路由
  // next: Function: 必定要調用該方法來 resolve 這個鉤子。執行效果依賴 next 方法的調用參數
})
複製代碼

全局後置鉤子

router.afterEach((to, from) => {
  // ...
})
複製代碼

3.6 路由元信息

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      children: [
        {
          path: 'bar',
          component: Bar,
          // a meta field
          meta: { requiresAuth: true }
        }
      ]
    }
  ]
})

// 訪問meta對象
// 一個路由匹配到的全部路由記錄會暴露爲 $route 對象 (還有在導航守衛中的路由對象) 的 $route.matched 數組。所以,咱們須要遍歷 $route.matched 來檢查路由記錄中的 meta 字段。
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // this route requires auth, check if logged in
    // if not, redirect to login page.
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // 確保必定要調用 next()
  }
})
複製代碼

3.7 路由懶加載

使用動態 import語法來定義代碼分塊點 (split point): 若是您使用的是 Babel,你將須要添加 syntax-dynamic-import 插件,才能使 Babel 能夠正確地解析語法。ui

const router = new VueRouter({
  routes: [
    { path: '/foo', component: () => import('./Foo.vue') }
  ]
})
複製代碼
相關文章
相關標籤/搜索