1.简单的路由嵌套例子
需要注意在要嵌套的路由最后添加children,写成数组对象形式
添加相对应的路径,把需要嵌套的内容写入想要嵌套的标签中,使用
<router-link to='/路径/下一路径'>登录</router-link>,然后添加对应的内容
<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' //修改默认的类名
})
//5.
new Vue({
el:'#app',
router:router
})
</script>
当点击注册时的效果截图
1.png
2.路由的传参
简单的两种类型
1.查询字符串
/user/regist?name=jack&age=18
接收:{{$route.query}}
2.rest风格
/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}, //显示当前首要根目录内容
{path:'/home',component:Home},
{
path:'/user',
component:User,
children:[ //嵌套在哪个路径下就写在相应路径下
{path:'regist',component:Regist},
{path:'login/:userName/:userage',component:Login}
]
}
]
//4.
const router=new VueRouter({
routes:routes,
linkActiveClass:'active' //修改默认的类名
})
//5.
new Vue({
el:'#app',
router:router
})
</script>
效果如下图:
注册:查询字符串的方法
2.png
登录:rest风格的方法
3.png
网友评论