cnode社區(qū)

面試要點(diǎn):(單頁應(yīng)用重點(diǎn)在vue-router)

  1. 單頁應(yīng)用,頁面只有一個 APP組件;
  2. vue-router實(shí)現(xiàn)頁面內(nèi)視圖跳轉(zhuǎn),多個router-view可以顯示多個組件,router-view根據(jù)路由的定位顯示組件;
    APP.vue項目結(jié)構(gòu):
<div id="app">
    <Header></Header>
    <div class="main">
        <router-view name="slidebar"></router-view>
        <router-view name="main"></router-view>
    </div>
</div>
  1. 路由的配置結(jié)構(gòu)
export default new Router({
  routes: [
    {
      name: 'root',
      path: '/',
      components:{
        main: PostList
      }
    },
    {
      name: 'post_content',
      path:'/topic/:id&author=:name',
      components:{
        main:Article,
        slidebar: SlideBar,
      }
    },
    {
      name:'user_info',
      path: '/userinfo/:name',
      components:{
        main: UserInfo,
      }
    }
  ]
})
  • 路由的跳轉(zhuǎn)路徑path可以設(shè)置參數(shù)(前面加:),參數(shù)由router-link提供,
<router-link :to="{name:'post_content',params:{id:post.id,name:post.author.loginname}}">
  • 路由跳轉(zhuǎn)后,個人詳情頁(userInfo)和文章詳情頁(Article)發(fā)送請求獲得數(shù)據(jù)時需要拿到此時路由的上的參數(shù);this.$route.params.XXX
getArticleData(){
  this.$http.get(`https://cnodejs.org/api/v1/topic/${this.$route.params.id}`)
    .then(res=>{
      if(res.data.success == true){
        this.isLoading = false
        this.post = res.data.data
       }
     })
    .catch(err=>{console.log(err)})
}

總結(jié):

router-link 動態(tài)綁定 to 屬性指定跳轉(zhuǎn)的路由name并提供路由需要的參數(shù)
router配置里path需要的參數(shù)和vue組件獲取路由上的參數(shù)都來自router-link。

  1. watch 監(jiān)聽路由的變化
    當(dāng)路由變化時,需要重新請求數(shù)據(jù)更新頁面,例如在文章詳情頁點(diǎn)開了另一篇文章的鏈接,根據(jù)路由的變化,重新發(fā)送請求拿到數(shù)據(jù),所以要使用watch屬性監(jiān)聽$route
watch:{
  $route: function(to,from){
    this.getArticleData()
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容