使用 Vue.js 搭配 vue-router 建立單頁應用(SPA)非常簡單:只需配置組件與路由映射,再告訴 vue-router 在哪裡渲染即可。本文分為「普通方式」與「在 vue-cli 中的模塊化用法」兩部分說明。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vue-router使用方法</title>
</head>
<body>
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 組件來導航,to 屬性指定鏈接,預設渲染為 a 標籤 -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由出口:匹配到的組件渲染於此 -->
<router-view></router-view>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router"></script>
<script>
// 1. 定義路由組件
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
});
// 4. 建立並掛載根實例,記得透過 router 參數注入路由
const app = new Vue({ router }).$mount('#app');
</script>
</body>
</html>
先安裝 vue-router 插件:
npm install vue-router --save-dev
在 src/components 下建立 Foo.vue 與 Bar.vue:
<!-- Foo.vue --> <template> <div>foo</div> </template>
<!-- Bar.vue --> <template> <div>bar</div> </template>
修改 App.vue,用 router-view 把組件掛載進來:
<template> <div id="app"> <router-view class="view" keep-alive transition transition-mode="out-in"></router-view> </div> </template>
修改 main.js:
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import Foo from './components/Foo'
import Bar from './components/Bar'
const routes = [
{ path: '/foo/', component: Foo },
{ path: '/bar/', component: Bar }
]
const router = new VueRouter({ routes })
new Vue({
router,
el: '#app',
render: h => h(App)
})
完成後執行 npm run dev 即可查看效果。整體流程就是:定義組件 → 配置路由映射 → 建立 router 實例 → 注入根實例,並用 router-view 作為路由出口。