利用vue-router實現(xiàn)二級菜單內(nèi)容轉(zhuǎn)換
二級菜單導(dǎo)航是一種很普遍的功能,一般網(wǎng)頁都會有這個功能。如果是平常的做法就是改變url,跳到相應(yīng)的頁面;還有一種就是frame。
如果用vue的話,可以用vue-router改變<router-view>里面的組件,這樣就能做到不刷新頁面都能跳到相應(yīng)“頁面”。其實url地址還是變了,但是他沒有刷新頁面其他位置的內(nèi)容,只是改變了<router-view>里面的組件,渲染了新的組件。
在線demo:http://runjs.cn/code/9th3cgxo
html
使用 Vue.js 時,我們就已經(jīng)把組件組合成一個應(yīng)用了,當你要把 vue-router 加進來,只需要配置組件和路由映射,然后告訴 vue-router 在哪里渲染它們。
<div id="app"> <div class="leftBox"> <!-- 使用 router-link 組件來導(dǎo)航. --> <!-- 通過傳入 `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
定義路由。每個路由應(yīng)該映射一個組件。 其中”component” 可以是組件等。 創(chuàng)建和掛載根實例。記得要通過 router 配置參數(shù)注入路由,從而讓整個應(yīng)用都有路由功能
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
})
切換到了文章部分時,我又弄了個文章列表,點擊文章標題才進入文章內(nèi)容。
- 這里我寫死了數(shù)據(jù),實際可以通過ajax拿到數(shù)據(jù)賦值。
- 我模擬了loading…,根據(jù)數(shù)據(jù)驅(qū)動的思維,通過v-if="loading"來判斷這個loading是否出現(xiàn)。
- 動畫切換記得要指定不同的key,不然是沒有效果的。
- 創(chuàng)建和改變路由的時候,都要通過傳遞url的參數(shù)去一個方法拿到數(shù)據(jù),這里就要created和watch '$route'
- 拿url參數(shù)是通過$route.params或$route.query等,具體看教程
- 返回上一級是用router.go(-1),相當于按退回按鈕
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);
}
}
}
本文已被整理到了《Vue.js前端組件學習教程》,歡迎大家學習閱讀。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue利用全局導(dǎo)航守衛(wèi)作登錄后跳轉(zhuǎn)到未登錄前指定頁面的實例代碼
這篇文章主要介紹了vue利用全局導(dǎo)航守衛(wèi)作登錄后跳轉(zhuǎn)到未登錄前指定頁面,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05

