學習路由器vue-router

vue-router:vue官方路由管理器。vue

功能:
嵌套的路由/視圖表
模塊化的、基於組件的路由配置
路由參數、查詢、通配符
基於 Vue.js 過渡系統的視圖過渡效果
細粒度的導航控制
帶有自動激活的 CSS class 的連接
HTML5 歷史模式或 hash 模式,在 IE9 中自動降級
自定義的滾動條行爲vue-router

安裝及建立router對象

安裝 npm i vue-router npm

1.建立單條路由瀏覽器

let index = {path:/index,name:'index',component:映射index的組件}

2.將多條路由合併爲一組模塊化

let routes = [
    index,
    頁面2,
    頁面3
]

3建立路由對象this

const router = new VueRouter({routes})

4在根實例上引用url

new Vue({
    router
 }).$mount(root)

使用router及傳參

一、以params做爲參數傳遞
建立路由
```
const pageA = {
    path:'/pageA/:id', //id是動態傳遞的參數
    name:'contentA', //與router-link中to屬性的name對應
    component:pageA //pageA的組件
    }
```
跳轉路由的連接
```
<router-link :to="{name:'contentA',params:{id:1,name:'pageA'}}">
  Go to PageA
</router-link>
```
或者傳path屬性
```
<router-link :to="{path:`/learnRouter/contentA/${id}`}">
    Go to PageA
</router-link>
```
頁面跳轉成功後瀏覽器url爲顯示爲 /pageA/id
this.$route.params.id來獲取

2.以query做爲參數傳遞
const pageA = {
        path:'/pageA, //以query做爲參數傳不須要在path後面加動態屬性
        name:'contentA', //與router-link中to屬性的name對應
        component:pageA //pageA的組件
        }
跳轉路由的組件
```
<router-link :to="{name:'contentB',query:{id:2}}">
    Go to PageA
</router-link>
```
瀏覽器url上顯示爲/pageA?id=1
this.$route.query.id獲取

在任何組件中均可以經過this.$router 得到路由對象,this.$route訪問的當前路由code


導航守衛

全局導航守衛,頁面每一次跳轉均可以監聽,也能夠放到組件中單獨使用component

router.beforeRouteUpdate (to, from, next) {
    // to 來自哪裏
    // from 前往哪裏
    //next() 來resolve這個鉤子的方法,若是不調用就不會完成跳轉
    //next('/other') 跳到另一個頁面
    //next(false) 終止跳轉 
  }

視圖
router-link跳轉的組件須要加上視圖router-view才能顯示,
當一個頁面有多個視圖時用name來區分router

視圖命名,路由裏的component裏的name爲鍵名對應router-view name=a

<router-view name="a"></router-view>
//路由
const pageA = {
    path:'/pageA',
    components:{
        a:pageA.vue
    }
//這條路由的意思是跳轉到/pageA時顯示name爲a的視圖,name=a的視圖對應的組件也就是pageA.vue

嵌套路由
例如須要一個tab導航欄,單擊菜單時切換組件,可是導航菜單不變。

const route = [
    {
        path:'/index',
        name:'index',
        //這裏定義子路由
        children:[
            {
                path:'/index/pageA',
                name:'pageA',
                component:pageA
             },
             {
                path:'/index/pageB',
                name:'pageB',
                component:pageB
             }
        ]
   }]
<router-link path="/pageA">goto pageA </router-link>
<router-link path="/pageB">goto pageB </router-link>
<router-view></router-view>
相關文章
相關標籤/搜索