1.什么是前端路由?
前端路由是根據(jù)不同的URL地址顯示不同的內(nèi)容或頁(yè)面。
2.什么時(shí)候使用前端路由?
在單頁(yè)面應(yīng)用時(shí),大部分頁(yè)面結(jié)構(gòu)不變,只改變部分內(nèi)容的時(shí)候應(yīng)用。
SPA:?jiǎn)雾?yè)web應(yīng)用,就是只有一張web頁(yè)面的應(yīng)用,是加載單個(gè)HTML頁(yè)面并在用戶與應(yīng)用程序交互時(shí),動(dòng)態(tài)更新的web應(yīng)用程序。
3.vue前端路由——vue-router
vue-router是用來(lái)構(gòu)建SPA(single page web application)的關(guān)鍵。
4.vue-router使用
HTML
<router-link></router-link>
JS
this.$router.push({path:' '});
5.vue-router分類:動(dòng)態(tài)路由、嵌套路由、編程式路由、命名路由和命名空間
1.動(dòng)態(tài)路由
export default new Router({
routes: [
{
path:'detail/:detailId',
name:'Detail',
component:Detail
}
]
})
訪問(wèn)http://localhost:18080/#/detail/123即可查看detailId為123的detail頁(yè)面
2.嵌套路由
export default new Router({
routes: [
{
path:'detail',
name:'Detail',
component:Detail,
children:[
{
path:'text',
name:'text',
component:Text
}
]
}
]
})
<router-link to="/detail/text">顯示detail詳情頁(yè)文本信息</router-link>
<div>
<router-view></router-view>//router-view是一個(gè)載體,專門用來(lái)承擔(dān)組件渲染,在Detail頁(yè)面中定義router-view定義一個(gè)載體用來(lái)渲染
</div>
在detail組件中,點(diǎn)擊router-link按鈕,訪問(wèn)http://localhost:18080/#/detail/text鏈接,即可查看detail的子頁(yè)面text頁(yè)面
3.編程式路由(通過(guò)js來(lái)實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn))
$router.push("name")
$router.push({path:"name"})
$router.push({path:"name?id=123"})
$router.push({path:"name",query:{id:123})
$router.go(1)
4.命名路由和命名空間
命名路由(給路由定義不同的名字,根據(jù)名字進(jìn)行匹配)
export default new Router({
routes: [
{
path:'detail:detailId',
name:'Detail',
component:Detail
}
]
})
通過(guò)name來(lái)跳轉(zhuǎn)路由
<router-link :to="{name:'Detail',params:{detailId:123}}"></router-link>
命名空間(給不同的router-view定義名字,router-link通過(guò)名字進(jìn)行對(duì)應(yīng)組件的渲染。)
export default new Router({
routes: [
{
path: '/detail',
name: 'Detail',
components:{
default:Detail,
text:Text,
img:Img,
}
}
]
})
<router-view></router-view>//渲染detail組件
<router-view name="text" ></router-view>//渲染text組件
<router-view name="img"></router-view>//渲染img組件