vue-router
用 Vue.js + vue-router 創(chuàng)建單頁(yè)應(yīng)用族跛,是非常簡(jiǎn)單的鞍爱。使用 Vue.js 初肉,我們已經(jīng)可以通過(guò)組合組件來(lái)組成應(yīng)用程序呻惕,當(dāng)你要把 vue-router 添加進(jìn)來(lái)荆责,我們需要做的是,將組件(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 組件來(lái)導(dǎo)航. -->
<!-- 通過(guò)傳入 `to` 屬性指定鏈接. -->
<!-- <router-link> 默認(rèn)會(huì)被渲染成一個(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)來(lái)
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. 定義路由
// 每個(gè)路由應(yīng)該映射一個(gè)組件。 其中"component" 可以是
// 通過(guò) Vue.extend() 創(chuàng)建的組件構(gòu)造器键耕,
// 或者寺滚,只是一個(gè)組件配置對(duì)象。
// 我們晚點(diǎn)再討論嵌套路由屈雄。
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. 創(chuàng)建 router 實(shí)例村视,然后傳 `routes` 配置
// 你還可以傳別的配置參數(shù), 不過(guò)先這么簡(jiǎn)單著吧。
const router = new VueRouter({
routes // (縮寫(xiě))相當(dāng)于 routes: routes
})
// 4. 創(chuàng)建和掛載根實(shí)例酒奶。
// 記得要通過(guò) 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>