vue-router
用 Vue.js + vue-router 創(chuàng)建單頁應(yīng)用,是非常簡單的。使用 Vue.js ,我們已經(jīng)可以通過組合組件來組成應(yīng)用程序,當(dāng)你要把 vue-router 添加進(jìn)來,我們需要做的是,將組件(components)映射到路由(routes),然后告訴 vue-router 在哪里渲染它們。下面是個(gè)基本例子:
<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 組件來導(dǎo)航. -->
<!-- 通過傳入 `to` 屬性指定鏈接. -->
<!-- <router-link> 默認(rèn)會被渲染成一個(gè) `<a>` 標(biāo)簽 -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的組件將渲染在這里 -->
<router-view></router-view>
</div>
// 1. 定義(路由)組件。
// 可以從其他文件 import 進(jìn)來
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. 定義路由
// 每個(gè)路由應(yīng)該映射一個(gè)組件。 其中"component" 可以是
// 通過 Vue.extend() 創(chuàng)建的組件構(gòu)造器,
// 或者,只是一個(gè)組件配置對象。
// 我們晚點(diǎn)再討論嵌套路由。
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. 創(chuàng)建 router 實(shí)例,然后傳 `routes` 配置
// 你還可以傳別的配置參數(shù), 不過先這么簡單著吧。
const router = new VueRouter({
routes // (縮寫)相當(dāng)于 routes: routes
})
// 4. 創(chuàng)建和掛載根實(shí)例。
// 記得要通過 router 配置參數(shù)注入路由,
// 從而讓整個(gè)應(yīng)用都有路由功能
const app = new Vue({
router
}).$mount('#app')
// 現(xiàn)在,應(yīng)用已經(jīng)啟動(dòng)了!
路由配合運(yùn)動(dòng)
<transition enter-active-class="animated rollIn" leave-active-class="animated rollOut">
<router-view></router-view>
</transition>