一,安裝
1)npm install vue-router
2)如果在一個模塊化工程中使用它,必須要通過 Vue.use()
明確地安裝路由功能:
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
如果使用全局的 script 標簽,則無須如此(手動安裝)。
二,使用
// 0. 如果使用模塊化機制編程,導入Vue和VueRouter,要調用 Vue.use(VueRouter) // 1. 定義(路由)組件。 // 可以從其他文件 import 進來 const Foo = { template: '<div>foo</div>' } const Bar = { template: '<div>bar</div>' } // 2. 定義路由 // 每個路由應該映射一個組件。 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')
<!--這里的 <router-view> 是最頂層的出口,渲染最高級路由匹配到的組件。同樣地,一個被渲染組件同樣可以包含自己的嵌套 <router-view>--> <div id="app"> <router-view></router-view> </div>
//要在嵌套的出口中渲染組件,需要在 VueRouter 的參數中使用 children 配置 const router = new VueRouter({ routes: [ { path: '/', redirect: '/main'//重定向
},
{ path: '/main', component: MainView, children: [ { path: '/main/visaindex', component: visaIndex }, { path: '/main/personal', component: Personal } ] } ] });
除了使用 <router-link> 創建 a 標簽來定義導航鏈接,我們還可以借助 router 的實例方法,通過編寫代碼來實現。
1)router.push(location)
這個方法會向 history 棧添加一個新的記錄,所以,當用戶點擊瀏覽器后退按鈕時,則回到之前的 URL。
當你點擊 <router-link> 時,這個方法會在內部調用,所以說,點擊 <router-link :to="..."> 等同於調用router.push(...)。
2)router.replace(location)
跟 router.push 很像,唯一的不同就是,它不會向 history 添加新記錄,而是跟它的方法名一樣 —— 替換掉當前的 history 記錄。
點擊<router-link :to="..." replace>等同於調用router.replace(...)。
3)router.go(n)
這個方法的參數是一個整數,意思是在 history 記錄中向前或者后退多少步。
4)『導航』表示路由正在發生改變。vue-router
提供的導航鈎子主要用來攔截導航,讓它完成跳轉或取消。
//使用 router.beforeEach
注冊一個全局的 before
鈎子
router.beforeEach(function(to, from, next) {
next();//確保要調用 next 方法,否則鈎子就不會被 resolved。
})
當一個導航觸發時,全局的 before 鈎子按照創建順序調用。每個鈎子方法接收三個參數:
1)to: Route
: 即將要進入的目標 路由對象
2)from: Route
: 當前導航正要離開的路由
3)next: Function
: 一定要調用該方法來resolve這個鈎子。
//注冊一個全局的 after
鈎子
router.afterEach(function(route) {
//...
})