前言
最近練習Vue,看到官方文檔中的嵌套路由,
不做不知道,實在是太坑了,網上資料demo少之又少,然后自己就做了一個demo,用了vue2.0嵌套路由實現豆瓣電影分頁功能,供大家學習學習,寫得不好望見諒。
官方文檔給出的demo:http://jsfiddle.net/yyx990803/L7hscd8h/
本demo地址:https://github.com/liangxiaoxin/doubandemo
demo截圖:
douban.gif
Demo簡單介紹
主路由:Top250(charts),正在熱映(hot),即將上映(ing),新片榜(newmovie)
const router = new VueRouter({
routes: [
{
path: '/', //設置默認路由為Top250
component: charts
},
{
path: '/charts', //Top250
component: charts
},
{
path: '/hot',
component: hot
},
{
path: '/ing',
component: ing
},
{
path: '/newmovie',
component: newmovie
},
]
}
在top250(charts)上添加了分頁功能作為子路由,在配置上添加:
{
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>
子路由如何跳轉同一組件時數據實現更新?
同樣,在top250(charts)上添加了分頁功能作為子路由,但指向同一組件:
{
path: '/charts/:id', //子路由
component: charts,
children: [
{path: '1', component: moviecontent2}, // 同一組件
{path: '2', component: moviecontent2}, // 同一組件
{path: '3', component: moviecontent2} // 同一組件
]
}
畫重點:
因為路由切換同一組件時,實例已經在第一次進入路由時創建了,之后切換路由不會被創建了,所以只能調用一次created,因此要使用$route監聽getData方法,當路由切換的時候,調用getData方法,重新獲取數據。
created: function () {
//第一次進入路由時數據的更新
this.$http.jsonp()
},
watch: {
'$route': 'getData' //切換路由,調用getData方法
},
methods: {
getData: function () {
//路由切換,重新請求數據
this.$http.jsonp()
}
}
數據來自豆瓣電影API。
代碼寫得好爛,湊合著看吧,反正子路由還是成功的啊!哈哈哈
有興趣的朋友可以看看我寫的豆瓣webapp
豆瓣web-app demo地址:https://liangxiaoxin.github.io/douban-webapp/
demo演示:
moviegif.gif