二級菜單導航是絕大多數網站都會有的功能。傳統做法要嘛改變網址跳到對應頁面,要嘛用 iframe 框架。若使用 Vue.js,則可透過 vue-router 改變 <router-view> 內的組件,做到不重整頁面就能切換「頁面」。此時網址雖然變了,但頁面其他位置不重整,只重新渲染 router-view 裡的組件——這正是 SPA 的核心精神。
線上 demo:https://runjs.cn/code/9th3cgxo
HTML
使用 Vue.js 時,我們已把組件組合成一個應用;要加入 vue-router,只需設定組件與路由對應,再告訴 vue-router 在哪裡渲染它們:
<div id="app"> <div class="leftBox"> <!-- 使用 router-link 組件來導航. --> <!-- 通過傳入 `to` 屬性指定鏈接. --> <!-- <router-link> 默認會被渲染成一個 `<a>` 標簽 --> <ul> <li><router-link to="/" actived>首頁</router-link></li> <li><router-link to="/article">文章</router-link></li> <li><router-link to="/picture">圖片</router-link></li> <li><router-link to="/music">音樂</router-link></li> </ul> </div> <div class="rightBox"> <!-- 路由出口 --> <!-- 路由匹配到的組件將渲染在這裡 --> <router-view></router-view> </div> </div>
JS
定義路由,每個路由對應一個組件,再建立並掛載根實例。記得要透過 router 設定參數注入路由,讓整個應用具備路由功能:
var Home = {template: '<div>home</div>'} var router = new VueRouter({ routes: [ {path: '/', component: Home}, {path: '/picture', component: Picture}, {path: '/music', component: Music}, {path: '/article', component: Artlist}, {path: '/article/:id', component: Article} ] }) new Vue({ el: "#app", router: router })
切換到文章部分時,這裡又做了一層文章列表,點擊標題才進入內容。幾個實作要點:
var Article = { template: '<div class="post">\ <div class="loading" v-if="loading">loading.....</div>\ <transition name="slide">\ <div v-if="post" class="content" :key="post.id">\ <button @click="back">返回</button>\ <p>{{post.title}}</p>\ <P>{{post.body}}</P>\ </div>\ </transition>\ </div>', data: function() { return { loading: false, error: null, post: null } }, created:function() { this.fetchData(); }, watch: { '$route': 'fetchData' }, methods: { fetchData:function () { this.error = this.post = null; this.loading = true; getPost(this.$route.params.id,(err,post) => { this.loading = false; if(err) { this.error = err.toString(); }else { this.post = post } }) }, back: function() { router.go(-1); } } }
透過 created 在進入時抓資料、watch '$route' 在路由變化時重新抓資料,再搭配 router.go(-1) 返回上一層,就能完成一個流暢的二級菜單導覽體驗。