VueRouter基礎

安裝

  1. 直接下載(官方CDN)

https://unpkg.com/vue-router/...
經過頁面script標籤引入,以下:html

<script src='https://unpkg.com/vue-router/dist/vue-router.js'></script>
  1. NPM安裝
npm install vue-router --save-dev

安裝完成後須要Vue.use()安裝此功能,例如:vue

import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

入門

  1. 簡單例子

<html>webpack

<!DOCTYPE html>
<html>
  <head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>vue1217</title>
  </head>
  <body>
<div id="app"></div>
<!-- built files will be auto injected -->
  </body>
</html>

<App.vue>web

<template>
  <div>
<p>
  <router-link to="/foo">Foo Link</router-link>
  <router-link to="/bar">Bar Link</router-link>
</p>
<router-view></router-view>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {};
</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>

<main.js>vue-router

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App';

Vue.use(VueRouter);

const foo = {
  template: '<div>foo</div>'
};
const bar = {
  template: '<div>bar</div>'
};

const routes = [{
  path: '/foo',
  component: foo
}, {
  path: '/bar',
  component: bar
}];

let router = new VueRouter({
  routes
});

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  render: h => h(App)
});
  1. 動態路由匹配

經過帶有冒號標記的屬性匹配,例如npm

path: '/foo/test0'
path: '/foo/test1'
均可以被
path: '/foo/:id'
匹配到
而且被匹配到的組件內部能夠經過
this.$route.params獲取到被匹配的參數
如上:
test0組件下的params參數爲
{
    id: 'test0'
}

一樣的:
/foo/test0/jason/0411
被
/foo/:id/:name/:birth
匹配到的參數如
{
    id: 'test0',
    name: 'jason',
    birth: '0411'
}

小提示:對於經過路由進行組件間的切換時,並不會來回構建組件實例,而是複用已存在的組件,想要監聽路由參數變化能夠經過watch屬性或者經過beforeRouteUpdate鉤子函數作操做瀏覽器

{
    watch: {
        '$route'(to, from) {
            // something to do
        }
    }
}
{
    beforeRouteUpdate(to, from, next) {
        // something to do
        next();// next必須執行否則的話beforeRouteUpdate鉤子函數不會resolved
    }
}
  1. 嵌套路由

顧名思義就是路由跳到的組件又包含有路由。
舉個栗子:app

<App.vue>
<template>
  <div>
<p>
  <router-link to="/foo">foo</router-link>
  <router-link to="/foo1/hm">foo1</router-link>
  <router-link to="/foo2/pf">foo2</router-link>
  <router-link to="/foo3/ps">foo3</router-link>
</p>
<router-view></router-view>
  </div>
</template>

const foo = {
  template: `
          <div>
            <p>{{ $route.params.id }}</p>
            <router-view></router-view>
          </div>
        `
};
<main.js>
const home = {
  template: '<div>home</div>'
};
const hm = {
  template: '<div>hm</div>'
};
const pf = {
  template: '<div>pf</div>'
};
const ps = {
  template: '<div>ps</div>'
};

const routes = [{
  path: '/:id',
  component: foo,
  children: [
{
  path: '',
  component: home
}, {
  path: 'hm',
  component: hm
}, {
  path: 'pf',
  component: pf
}, {
  path: 'ps',
  component: ps
}
  ]
}];
  1. 經過$router導航

在組件Vue實例內部能夠經過
this.$router.push(location, onComplete?, onAbort?)
this.$router.replace(location, onComplete?, onAbort?)
this.$router.go(n)ecmascript

// 字符串
router.push('home')
// 對象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
// 帶查詢參數,變成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

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

// 在瀏覽器記錄中前進一步,等同於 history.forward()
router.go(1)
// 後退一步記錄,等同於 history.back()
router.go(-1)
// 前進 3 步記錄
router.go(3)
// 若是 history 記錄不夠用,那就默默地失敗唄
router.go(-100)
router.go(100)
  1. 命名路由

在建立路由的時候能夠經過name屬性設置路由名稱函數

let routes = [{
    path: '/foo/:userId',
    name: 'test',
    component: User
}];

若是須要連接到這個命名路由咱們能夠醬紫

<router-link :to="{ 'name' : 'test', 'params' : { 'userId' : 410100 }}"></router-link>

也能夠醬紫

router.push({
    name: 'test',
    params: {
        userId: 410100
    }
});
  1. 命名視圖

不少時候咱們會碰到並存的多個視圖(router-view),咱們就須要爲視圖設置name沒有設置的爲default

<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
      }
    }
  ]
})
  1. 重定向
let routes = [{
  path: '/',
  redirect: '/goods'
},{
  path: '/goods',
  component: goods
}];
當path爲/的時候會自動重定向至/goods加載goods組件
固然也能夠經過name重定向,做用是相同的
let routes = [{
  path: '/',
  redirect: {
    name: 'goods'
  }
},{
  path: '/goods',
  name: 'goods',
  component: goods
}];
固然也能夠是一個方法
let routes = [{ path: '/a', redirect: to => {
  // 方法接收 目標路由 做爲參數
  // return 重定向的 字符串路徑/路徑對象
}}];
  1. 別名

別名與重定向只有一丟丟不一樣,重定向指/a路徑調到/b路徑加載,別名指仍是加載/a路徑只是加載內容是/b路徑下的

const router = new VueRouter({
  routes: [{ 
    path: '/a', 
    component: A, 
    alias: '/b' 
  }]
});

5.路由參數傳遞
有三種模式進行傳遞:布爾模式、對象模式、函數模式
布爾模式: 若是props被設置爲true,route.params將會被設置爲組件屬性。

router-link的路徑
<router-link to="/foo/params">foo</router-link>

foo的路由
{
  path: '/foo/:userName',
  name: 'foo',
  component: foo,
  props: true
}

foo組件
<template>
  <div>
    foo
    <div>{{userName}}</div>
  </div>
</template>

<script type="text/ecmascript-6">
  export default {
    props: {
      userName: {
        type: String,
        default: ''
      }
    }
  };
</script>

點擊router-link後的結果

clipboard.png

你會發現/foo/params被path匹配後

route.params =  {
    userName: 'params'
};

props中的userName就會接收到字符串'params',所以輸出結果如圖所示

對象模式:若是props是一個對象,它會被按原樣設置爲組件屬性。

{
  path: '/foo',
  name: 'foo',
  component: foo,
  props: {
    userName: 'From Obj'
  }
}

渲染後的結果:

clipboard.png

函數模式

{
  path: '/foo',
  name: 'foo',
  component: foo,
  props: (route) => ({userName: route.query.name})
}

看起來仍是很清楚的,只是props會接收一個當前的路由參數,將參數中的值轉換成你想要的值,以上三種模式天然也不影響經過router-view的v-bind:user-name這種方式傳遞,可是對於同名的參數值會有影響。

let lastProps = {};
let vBindProps = {
    userName: 'vBind',
    name: 'vBind'
};
let routeProps ={
    userName: 'route'
};
Object.assign(lastProps,vBindProps,routeProps);
// {userName: "route", name: "vBind"}
最終的lastProps就是傳入的props
相關文章
相關標籤/搜索