面試要點(diǎn):(單頁應(yīng)用重點(diǎn)在vue-router)
- 單頁應(yīng)用,頁面只有一個 APP組件;
-
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>
- 路由的配置結(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。
- watch 監(jiān)聽路由的變化
當(dāng)路由變化時,需要重新請求數(shù)據(jù)更新頁面,例如在文章詳情頁點(diǎn)開了另一篇文章的鏈接,根據(jù)路由的變化,重新發(fā)送請求拿到數(shù)據(jù),所以要使用watch屬性監(jiān)聽$route
watch:{
$route: function(to,from){
this.getArticleData()
}
}