【vue】--vueRouter

動態路由匹配

const router = new VueRouter({
  routes: [
    // 動態路徑參數 以冒號開頭
    { path: '/user/:id', component: User }
  ]
})
當匹配到一個路由時,參數值會被設置到 
this.$route.params

響應路由參數的變化

watch: {
    '$route' (to, from) {
      // 對路由變化做出響應...
    }
  }
 beforeRouteUpdate (to, from, next) {
    // react to route changes...
    // don't forget to call next()
  // 在當前路由改變,可是該組件被複用時調用 (動態路由) // 舉例來講,對於一個帶有動態參數的路徑 /foo/:id,在 /foo/1 和 /foo/2 之間跳轉的時候, // 因爲會渲染一樣的 Foo 組件,所以組件實例會被複用。而這個鉤子就會在這個狀況下被調用。 // 能夠訪問組件實例 `this`
  }

捕獲全部路由或 404 Not found 路由

{
  // 會匹配全部路徑
  path: '*'
}
{
  // 會匹配以 `/user-` 開頭的任意路徑
  path: '/user-*'
}

當使用一個通配符時,$route.params 內會自動添加一個名爲 pathMatch 參數。它包含了 URL 經過通配符被匹配的部分html

編程式的導航

router.push 方法。這個方法會向 history 棧添加一個新的記錄,因此,當用戶點擊瀏覽器後退按鈕時,則回到以前的 URL。vue

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

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

// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})

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

注意:若是提供了 pathparams 會被忽略,上述例子中的 query 並不屬於這種狀況。取而代之的是下面例子的作法,你須要提供路由的 name 或手寫完整的帶有參數的 pathreact

const userId = '123'
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 這裏的 params 不生效
router.push({ path: '/user', params: { userId }}) // -> /user

一樣的規則也適用於 router-link 組件的 to 屬性。編程

注意: 若是目的地和當前路由相同,只有參數發生了改變 (好比從一個用戶資料到另外一個 /users/1 -> /users/2),你須要使用 beforeRouteUpdate 來響應這個變化 (好比抓取用戶信息)。瀏覽器

 

命名視圖

若是 router-view 沒有設置名字,那麼默認爲 defaultide

  <router-link to="/">/</router-link>
  <router-link to="/other">/other</router-link>ui

<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>

一個視圖使用一個組件渲染,所以對於同個路由,多個視圖就須要多個組件。確保正確使用 components 配置 (帶上 s)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]
})

 

重定向和別名

重定向也是經過 routes 配置來完成,下面例子是從 /a 重定向到 /b:

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' }
  ]
})
重定向的目標也能夠是一個命名的路由:

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: { name: 'foo' }}
  ]
})
甚至是一個方法,動態返回重定向目標:

const router = new VueRouter({
  routes: [
    { path: '/a', redirect: to => {
      // 方法接收 目標路由 做爲參數
      // return 重定向的 字符串路徑/路徑對象
    }}
  ]
})
注意導航守衛並無應用在跳轉路由上,而僅僅應用在其目標上。在下面這個例子中,爲 /a 路由添加一個 beforeEach 或 beforeLeave 守衛並不會有任何效果。

別名

const router = new VueRouter({
  routes: [
    { path: '/a', component: A, alias: '/b' }
  ]
})
相關文章
相關標籤/搜索