<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<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>
<!-- 路由出口 -->
<!-- 路由匹配到的組件將渲染在這裏 -->
<router-view></router-view>
</div>
<script type="text/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')
// 現在,應用已經啓動了!
</script>
</body>
</html>
實現效果:點擊導航進入到組件
感受:
第一次接觸vue-router,通過定義路由(引入組件)、定義路由(定義路徑和響應的組件)、創建router實例、創建和掛在根實例這幾個步驟,很方便的實現了無刷新頁面跳轉。
vue、grunt、jquery等等這樣的庫、框架和工具需要花時間去學習,但是永遠不變的是原生JavaScript!!所以一定要打好JS基礎,用框架錦上添花~