vue-router相關

vue-router@3.0+javascript

vue@2.5+html

基礎部分

1. 動態路由配置

router.js 中相關代碼vue

// 測試模塊
    {
        path: '/Test01/:id',
        name: 'Test01',
        component: Test01,
        children: [],
        meta: {
            requireAuth: false,
            title: '測試一'
        }
    },

頁面跳轉相關代碼java

<router-link class="tab" to="/test01/aaaaaaaaaaaaaaaaaa">Go to Foo</router-link>
/**
* 或者使用編程式
**/
router.push({ name: 'test01', params: { userId: aaaaaaaaaaaaaaaaaa }})

 

結果:vue-router

路由路徑是:「http://192.168.3.3:1791/demo.html#/test01/aaaaaaaaaaaaaaaaaa」編程

參數是:this.$route.params.id = "aaaaaaaaaaaaaaaaaa"ide

2. 嵌套路由

router.js中相關代碼佈局

{
        path: '/index',
        name: 'index',
        component: Index,
        children: [
            // 測試模塊
            {
                path: 'Test01',  // 這裏是只 /index/Test01 ,若是加"/",則指根目錄
                component: Test01,
                meta: {
                    requireAuth: false
                }
            },
            // 測試模塊
            {
                path: 'Test02',
                name: 'Test02',
                component: Test02,
                meta: {
                    requireAuth: false
                }
            }
        ],
        meta: {
            requireAuth: false,
            keepAlive: true,
            title: '測試'
        }
    }

頁面跳轉相關代碼:測試

<div class="tablist">
    <router-link class="tab" to="/index/test01">Go to Foo</router-link>
    <router-link class="tab" to="/index/test02" tag="div">Go to Bar</router-link>
</div>
<router-view ></router-view>

這裏路徑從根目錄開始指定。ui

3. 編程式導航

  • router.push(location, onComplete?, onAbort?)
  • router.replace(location, onComplete?, onAbort?)
  • router.go(n)

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

4. 命名視圖

/*
有時候想同時 (同級) 展現多個視圖,而不是嵌套展現,例如建立一個佈局,有 sidebar (側導航) 和 main (主內容) 兩個視圖,這個時候命名視圖就派上用場了。你能夠在界面中擁有多個單獨命名的視圖,而不是隻有一個單獨的出口。若是 router-view 沒有設置名字,那麼默認爲 default。
*/

// HTML 部分代碼
<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>

// 路由部分代碼
{
    path: '/',
    components: {
        default: Foo,
        a: Bar,
        b: Baz
    }
}

5. 重定向

  • 基本的重定向
// 路徑
{ path: '/a', redirect: '/b' },
// name
{ path: '/a', redirect: { name: 'foo' }}
  • 動態返回重定向目標
{ path: '/a', redirect: to => {
    // 方法接收 目標路由 做爲參數
    // return 重定向的 字符串路徑/路徑對象
}}

6. 別名(alias)

{ path: '/a', component: A, alias: '/b' }

進階部分

略...

相關文章
相關標籤/搜索