vue2.0嵌套路由實現(xiàn)豆瓣電影分頁功能(附demo)

前言

創(chuàng)新互聯(lián)建站主營化隆網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶APP開發(fā),化隆h5微信平臺小程序開發(fā)搭建,化隆網(wǎng)站營銷推廣歡迎化隆等地區(qū)企業(yè)咨詢

最近練習(xí)Vue,看到官方文檔中的嵌套路由,不做不知道,實在是太坑了,網(wǎng)上資料demo少之又少,然后自己就做了一個demo,用了vue2.0嵌套路由實現(xiàn)豆瓣電影分頁功能,供大家學(xué)習(xí)學(xué)習(xí),寫得不好望見諒。

demo截圖:

vue2.0嵌套路由實現(xiàn)豆瓣電影分頁功能(附demo)

Demo簡單介紹

主路由:Top250(charts),正在熱映(hot),即將上映(ing),新片榜(newmovie)

const router = new VueRouter({
  routes: [
    {
     path: '/',  //設(shè)置默認(rèn)路由為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>

子路由如何跳轉(zhuǎn)同一組件時數(shù)據(jù)實現(xiàn)更新?

同樣,在top250(charts)上添加了分頁功能作為子路由,但指向同一組件:

{
 path: '/charts/:id', //子路由
 component: charts,
 children: [
  {path: '1', component: moviecontent2}, // 同一組件
  {path: '2', component: moviecontent2}, // 同一組件
  {path: '3', component: moviecontent2} // 同一組件
  ]
}

畫重點:

因為路由切換同一組件時,實例已經(jīng)在第一次進(jìn)入路由時創(chuàng)建了,之后切換路由不會被創(chuàng)建了,所以只能調(diào)用一次created,因此要使用$route監(jiān)聽getData方法,當(dāng)路由切換的時候,調(diào)用getData方法,重新獲取數(shù)據(jù)。

created: function () {
    //第一次進(jìn)入路由時數(shù)據(jù)的更新
    this.$http.jsonp()
},
watch: {
 '$route': 'getData' //切換路由,調(diào)用getData方法
},
methods: {
 getData: function () {
    //路由切換,重新請求數(shù)據(jù)
    this.$http.jsonp()
 }
}

數(shù)據(jù)來自豆瓣電影API。

代碼寫得好爛,湊合著看吧,反正子路由還是成功的啊!

本demo地址:doubandemo_jb51.rar

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

當(dāng)前文章:vue2.0嵌套路由實現(xiàn)豆瓣電影分頁功能(附demo)
路徑分享:http://bm7419.com/article20/pcggco.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、小程序開發(fā)、云服務(wù)器App開發(fā)、企業(yè)建站用戶體驗

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)頁設(shè)計公司