首頁  >  文章  >  web前端  >  舉例說明Vue Router路由重定向與別名設定

舉例說明Vue Router路由重定向與別名設定

藏色散人
藏色散人轉載
2022-08-10 14:16:001732瀏覽

重定向

舉例說明:重定向是指當使用者存取/home#時,URL 會被/ 替換,然後配對成/

重定向也是透過routes 設定來完成,下面範例是從/home 重定向到/

const routes = [{ path: '/home', redirect: '/' }]

重定向的目標也可以是一個命名的路由:

const routes = [{ path: '/home', redirect: { name: 'homepage' } }]

也可以是一個方法,動態返回重定向目標:

const routes = [
  {
    // /search/screens -> /search?q=screens
    path: '/search/:searchText',
    redirect: to => {
      // 方法接收目标路由作为参数
      // return 重定向的字符串路径/路径对象
      return { path: '/search', query: { q: to.params.searchText } }
    },
  },
  {
    path: '/search',
    // ...
  },]

別名

#將 / 別名/home,意味著當用戶訪問/home 時,URL 仍然是/home,但會被匹配為用戶正在訪問/

const routes = [{ path: '/', component: Homepage, alias: '/home' }]

透過別名,可以自由地將 UI 結構對應到一個任意的 URL,而不受配置的巢狀結構的限制。使別名以 / 開頭,以使巢狀路徑中的路徑成為絕對路徑。甚至可以將兩者結合起來,用一個陣列提供多個別名

const routes = [
  {
    path: '/users',
    component: UsersLayout,
    children: [
      // 为这 3 个 URL 呈现 UserList
      // - /users
      // - /users/list
      // - /people
      { path: '', component: UserList, alias: ['/people', 'list'] },
    ],
  },]

#/people 是絕對路徑的寫法,即可以直接通過 /people 來訪問。
list 是相對路徑的寫法,即url會拼接父級的路徑 → /users/list。

注意:如果路由有參數,請確保在任何絕對別名中包含它們:

const routes = [
  {
    path: '/users/:id',
    component: UsersByIdLayout,
    children: [
      // 为这 3 个 URL 呈现 UserDetails
      // - /users/24
      // - /users/24/profile
      // - /24
      { path: 'profile', component: UserDetails, alias: ['/:id', ''] },
    ],
  },]

【相關推薦:vue.js影片教學

以上是舉例說明Vue Router路由重定向與別名設定的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除