Vue.js 路由容許咱們經過不一樣的 URL 訪問不一樣的內容。vue
經過 Vue.js 能夠實現多視圖的單頁Web應用(single page web application,SPA)。git
Vue.js 路由須要載入 vue-router 庫github
中文文檔地址:vue-router文檔。web
https://unpkg.com/vue-router/dist/vue-router.js
推薦使用淘寶鏡像:vue-router
cnpm install vue-router
Vue.js + vue-router 能夠很簡單的實現單頁應用。npm
如下實例中咱們將 vue-router 加進來,而後配置組件和路由映射,再告訴 vue-router 在哪裏渲染它們。代碼以下所示:編程
// 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')
// 如今,應用已經啓動了!app
能夠試一下模塊化