前言
最近練習(xí)Vue,看到官方文檔中的嵌套路由,
不做不知道,實(shí)在是太坑了,網(wǎng)上資料demo少之又少,然后自己就做了一個(gè)demo,用了vue2.0嵌套路由實(shí)現(xiàn)豆瓣電影分頁(yè)功能,供大家學(xué)習(xí)學(xué)習(xí),寫(xiě)得不好望見(jiàn)諒。
官方文檔給出的demo:http://jsfiddle.net/yyx990803/L7hscd8h/
本demo地址:https://github.com/liangxiaoxin/doubandemo
demo截圖:

Demo簡(jiǎn)單介紹
主路由:Top250(charts),正在熱映(hot),即將上映(ing),新片榜(newmovie)
const router = new VueRouter({
routes: [
{
path: '/', //設(shè)置默認(rèn)路由為T(mén)op250
component: charts
},
{
path: '/charts', //Top250
component: charts
},
{
path: '/hot',
component: hot
},
{
path: '/ing',
component: ing
},
{
path: '/newmovie',
component: newmovie
},
]
}
在top250(charts)上添加了分頁(yè)功能作為子路由,在配置上添加:
{
path: '/charts/:id', //子路由
component: charts,
children: [
{path: '1', component: moviecontent},
{path: '2', component: moviecontent2},
{path: '3', component: moviecontent3}
]
}
在charts組件上添加入口:
<router-link to="/charts/1">1</router-link>
<router-link to="/charts/2">2</router-link>
<router-link to="/charts/3">3</router-link>
在charts組件上添加出口:
<router-view></router-view>
子路由如何跳轉(zhuǎn)同一組件時(shí)數(shù)據(jù)實(shí)現(xiàn)更新?
同樣,在top250(charts)上添加了分頁(yè)功能作為子路由,但指向同一組件:
{
path: '/charts/:id', //子路由
component: charts,
children: [
{path: '1', component: moviecontent2}, // 同一組件
{path: '2', component: moviecontent2}, // 同一組件
{path: '3', component: moviecontent2} // 同一組件
]
}
畫(huà)重點(diǎn):
因?yàn)槁酚汕袚Q同一組件時(shí),實(shí)例已經(jīng)在第一次進(jìn)入路由時(shí)創(chuàng)建了,之后切換路由不會(huì)被創(chuàng)建了,所以只能調(diào)用一次created,因此要使用$route監(jiān)聽(tīng)getData方法,當(dāng)路由切換的時(shí)候,調(diào)用getData方法,重新獲取數(shù)據(jù)。
created: function () {
//第一次進(jìn)入路由時(shí)數(shù)據(jù)的更新
this.$http.jsonp()
},
watch: {
'$route': 'getData' //切換路由,調(diào)用getData方法
},
methods: {
getData: function () {
//路由切換,重新請(qǐng)求數(shù)據(jù)
this.$http.jsonp()
}
}
數(shù)據(jù)來(lái)自豆瓣電影API。
代碼寫(xiě)得好爛,湊合著看吧,反正子路由還是成功的啊!哈哈哈
有興趣的朋友可以看看我寫(xiě)的豆瓣webapp
豆瓣web-app demo地址:https://liangxiaoxin.github.io/douban-webapp/
demo演示:
