Vue.js路由管理器 Vue Router

起步

  • HTML
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

<div id="app">
  <h1>Hello App!</h1>
  <p>
    <!-- 使用 router-link 組件來導航. -->
    <!-- 經過傳入 `to` 屬性指定連接. -->
    <!-- <router-link> 默認會被渲染成一個 `<a>` 標籤 -->
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <!-- 路由出口 -->
  <!-- 路由匹配到的組件將渲染在這裏 n內置組件-->
  <router-view></router-view>
</div>
  • JavaScript
// 0. 若是使用模塊化機制編程,導入Vue和VueRouter,要調用 Vue.use(VueRouter)

// 1. 定義 (路由) 組件。
// 能夠從其餘文件 import 進來
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

// 2. 定義路由
// 每一個路由應該映射一個組件。 其中"component" 能夠是
// 經過 Vue.extend() 建立的組件構造器,
// 或者,只是一個組件配置對象。
// 咱們晚點再討論嵌套路由。
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

// 3. 建立 router 實例,而後傳 `routes` 配置
// 你還能夠傳別的配置參數, 不過先這麼簡單着吧。
const router = new VueRouter({
  routes // (縮寫) 至關於 routes: routes
})

// 4. 建立和掛載根實例。
// 記得要經過 router 配置參數注入路由,
// 從而讓整個應用都有路由功能
const app = new Vue({
  router
}).$mount('#app')

// 如今,應用已經啓動了!

經過注入路由器,咱們能夠在任何組件內經過 this.$router 訪問路由器,也能夠經過 this.$route 訪問當前路由:html

export default {
  computed: {
    username () {
      // 咱們很快就會看到 `params` 是什麼
      return this.$route.params.username
    }
  },
  methods: {
    goBack () {
      window.history.length > 1
        ? this.$router.go(-1)
        : this.$router.push('/')
    }
  }
}

routes 選項 (Array)

redirect(重定向 )

//此時訪問/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 重定向的 字符串路徑/路徑對象
    }}
  ]
})

命名路由

export default [
    {
        path:'/',
        redirect:'/app' //默認跳轉路由
    },
    {
        path: '/app',
        //路由命名,可用於跳轉
        name: 'app',
    }
]

//可用於跳轉
<router-link :to="{name:'app'}">app</router-link>

路由元信息

定義路由的時候能夠配置 meta 字段:vue

export default [
    {
        path:'/',
        redirect:'/app' //默認跳轉路由
    },
    {
        path: '/app',
        //**至關於HTML的meta標籤**
        meta: {
            title: 'this is app',
            description: 'asdasd'
        },
    }
]

嵌套路由

export default [
    {
        path:'/',
        redirect:'/app' //默認跳轉路由
    },
    {
        path: '/app',
        //子路由 匹配 /app/test
         children: [
           {
             path: 'test',
             component: Login
           }
         ]
    }
]

路由組件傳參

export default [
    {
        path:'/',
        redirect:'/app' //默認跳轉路由
    },
    {
        path: '/app/:id', // /app/xxx ,組件內部能夠經過$route.params.id拿到這個值
        // 會把:後面的參數經過props傳遞給組件Todozhong 中
        //布爾模式
        props: true,
        //對象模式
        props:{id:456}
        //函數模式
        props: (route) => ({ id: route.query.b }),
        component: Todo,

    }
]

mode選項(string)

vue-router 默認 hash 模式 —— 使用 URL 的 hash 來模擬一個完整的 URL,因而當 URL 改變時,頁面不會從新加載。vue-router

若是不想要很醜的 hash,咱們能夠用路由的 history 模式,這種模式充分利用 history.pushState API 來完成 URL 跳轉而無須從新加載頁面。編程

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

這種模式要玩好,還須要後臺配置支持。瀏覽器

base(string)

應用的基路徑。例如,若是整個單頁應用服務在 /app/ 下,而後 base 就應該設爲 "/app/"app

return new Router({
    routes,
    mode: 'history',//默認使用hash#
    base: '/base/', //在path前面都會加上/base/,基路徑
  })

linkActiveClass(string)

默認值: "router-link-active"ide

全局配置 <router-link> 的默認「激活 class 類名」。模塊化

return new Router({
    routes,
    mode: 'history',//默認使用hash#
    base: '/base/', //在path前面都會加上/base/,基路徑
    // 點擊calss名字
    linkActiveClass: 'active-link', //匹配到其中一個子集
    linkExactActiveClass: 'exact-active-link',//徹底匹配
  })

linkExactActiveClass(string)

默認值: "router-link-exact-active"函數

全局配置 <router-link> 精確激活的默認的 class。ui

scrollBehavior(Function)

路由跳轉後是否滾動

export default () => {
  return new Router({
    routes,
    mode: 'history',//默認使用hash#
    base: '/base/', //在path前面都會加上/base/,基路徑
    //頁面跳轉是否須要滾動
    /*
        to:去向路由,完整路由對象
        from:來源路由
        savedPosition:保存的滾動位置
    */
    scrollBehavior (to, from, savedPosition) {
      if (savedPosition) {
        return savedPosition
      } else {
        return { x: 0, y: 0 }
      }
    },
  })
}

parseQuery / stringifyQuery (Function)

/每次import都會建立一個router,避免每次都是同一個router
export default () => {
  return new Router({
    routes,
    mode: 'history',//默認使用hash#
    base: '/base/', //在path前面都會加上/base/,基路徑
    // 路由後面的參數?a=2&b=3,string->object
     parseQuery (query) {

     },
      //object->string
    stringifyQuery (obj) {

     }
  })
}

fallback(boolean)

當瀏覽器不支持 history.pushState 控制路由是否應該回退到 hash 模式。默認值爲 true。
若是設置爲false,則跳轉後刷新頁面,至關於多頁應用

<router-link>

過渡動效

<router-view> 是基本的動態組件,因此咱們能夠用 <transition> 組件給它添加一些過渡效果:

<transition>
  <router-view></router-view>
</transition>

高級用法

命名視圖

<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>

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

導航守衛

  • 全局守衛
import Vue from 'vue'
import VueRouter from 'vue-router'

import App from './app.vue'

import './assets/styles/global.styl'
// const root = document.createElement('div')
// document.body.appendChild(root)
import createRouter from './config/router'
Vue.use(VueRouter)

const router = createRouter()

// 全局導航守衛(鉤子)

// 驗證一些用戶是否登陸
router.beforeEach((to, from, next) => {
    console.log('before each invoked')
    next()
//   if (to.fullPath === '/app') {
//     next({ path: '/login' })
//     console.log('to.fullPath :'+to.fullPath )

//   } else {
//     next()
//   }
})

router.beforeResolve((to, from, next) => {
    console.log('before resolve invoked')
    next()
})

// 每次跳轉後觸發
router.afterEach((to, from) => {
    console.log('after each invoked')
})

new Vue({
    router,
    render: (h) => h(App)
}).$mount("#root")
  • 路由獨享的守衛

能夠在路由配置上直接定義 beforeEnter 守衛:

export default [
    {
        path:'/',
        redirect:'/app' //默認跳轉路由
    },
    {
  
        path: '/app',
        // 路由獨享的守衛鉤子
        beforeEnter(to, from, next) {
            console.log('app route before enter')
            next()
        }
        component: Todo,
    }
]
  • 組件內的守衛
export default {
  //進來以前
  beforeRouteEnter(to, from, next) {
    // 不!能!獲取組件實例 `this`
    // 由於當守衛執行前,組件實例還沒被建立
    console.log("todo before enter", this); //todo before enter undefined
    //能夠經過傳一個回調給 next來訪問組件實例。在導航被確認的時候執行回調,而且把組件實例做爲回調方法的參數。
    next(vm => {
        // 經過 `vm` 訪問組件實例
      console.log("after enter vm.id is ", vm.id);
    });
  },
  //更新的時候
  beforeRouteUpdate(to, from, next) {
    console.log("todo update enter");
    next();
  },
  // 路由離開
  beforeRouteLeave(to, from, next) {
    console.log("todo leave enter");
    const answer = window.confirm('Do you really want to leave? you have unsaved changes!')
      if (answer) {
        next()
      } else {
        //以經過 next(false) 來取消。
        next(false)
      }
  },
  props:['id'],
  components: {
    Item,
    Tabs
  },
  mounted() {
    console.log(this.id)
  },
};

路由懶加載

參考:路由懶加載

相關文章
相關標籤/搜索