1.簡單的路由嵌套例子
需要注意在要嵌套的路由最后添加children侈沪,寫成數(shù)組對象形式
添加相對應(yīng)的路徑裸弦,把需要嵌套的內(nèi)容寫入想要嵌套的標(biāo)簽中膏萧,使用
<router-link to='/路徑/下一路徑'>登錄</router-link>,然后添加對應(yīng)的內(nèi)容
<style>
.active{
color: red;
}
</style>
<div id='app'>
<router-link to='/home'>首頁</router-link>
<router-link to='/user'>用戶頁</router-link>
<router-view></router-view>
</div>
<script src='js/vue.js'></script>
<script src='js/vue-router.js'></script>
<script>
//2.
var Home={
template:`<h1>這是首頁</h1>`
}
var User={
template:`
<div>
<h1>這是用戶頁</h1>
<ul>
<li>
<router-link to='/user/regist'>注冊</router-link>
</li>
<li>
<router-link to='/user/login'>登錄</router-link>
</li>
</ul>
<router-view></router-view>
</div>
`
}
var Regist={
template:`<h3>這是注冊頁面</h3>`
}
var Login={
template:`<h3>這是登錄頁面</h3>`
}
//3.
const routes=[
{path:'/',component:Home},
{path:'/home',component:Home},
{
path:'/user',
component:User,
children:[
{path:'regist',component:Regist},
{path:'login',component:Login}
]
}
]
//4.
const router=new VueRouter({
routes:routes递沪,
linkActiveClass:'active' //修改默認(rèn)的類名
})
//5.
new Vue({
el:'#app',
router:router
})
</script>
當(dāng)點擊注冊時的效果截圖
2.路由的傳參
簡單的兩種類型
1.查詢字符串
/user/regist?name=jack&age=18
接收:{{$route.query}}
2.rest風(fēng)格
/user/login/jack/18
接收: {{$route.params}}
<style>
.active{
color: red;
}
</style>
<div id='app'>
<router-link to='/home'>首頁</router-link>
<router-link to='/user'>用戶頁</router-link>
<router-view></router-view>
</div>
<script src='js/vue.js'></script>
<script src='js/vue-router.js'></script>
<script>
//2.
var Home={
template:`<h1>這是首頁</h1>`
}
var User={
template:`
<div>
<h1>這是用戶頁</h1>
<ul>
<li>
<router-link to='/user/regist?uname=jack&&age=18'>注冊</router-link>
</li>
<li>
<router-link to='/user/login/alice/20'>登錄</router-link>
</li>
</ul>
<router-view></router-view>
</div>
`
}
var Regist={
template:`
<div>
<h3>這是注冊頁面</h3>
<a href=''>{{$route.query}}</a>
<ul>
<li>{{$route.query.uname}}</li>
<li>{{$route.query.age}}</li>
</ul>
</div>
`
}
var Login={
template:`
<div>
<h3>這是登錄頁面</h3>
<p>{{$route.params}}</p>
<ul>
<li>{{$route.params.userName}}</li>
<li>{{$route.params.userage}}</li>
</ul>
</div>
`
}
//3.
const routes=[
{path:'/',component:Home}, //顯示當(dāng)前首要根目錄內(nèi)容
{path:'/home',component:Home},
{
path:'/user',
component:User,
children:[ //嵌套在哪個路徑下就寫在相應(yīng)路徑下
{path:'regist',component:Regist},
{path:'login/:userName/:userage',component:Login}
]
}
]
//4.
const router=new VueRouter({
routes:routes勇蝙,
linkActiveClass:'active' //修改默認(rèn)的類名
})
//5.
new Vue({
el:'#app',
router:router
})
</script>
效果如下圖:
注冊:查詢字符串的方法
登錄:rest風(fēng)格的方法