路由的五个步骤
<!--路由是vue的插件和工具库(为了实现页面跳转)
作用:
1.根据不同的URL访问不同的页面
2.创建单页面应用spa(single page application)-->
<!-- 写路由的五个步骤:-->
<div class="box">
<!-- 1.写入链接标签和盛放标签-->
<router-link to='/home'>首页</router-link>
<router-link to='/user'>用户页</router-link>
<!--盛放每个页面对应的内容:-->
<router-view></router-view>
</div>
<!-- 导入js的顺序不能改变-->
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
<script>
//2.创建路由
var Home = {
template:`
<h1>这是首页</h1>
`
}
var User = {
template:`
<h1>这是用户页</h1>
`
}
//3.配置路由
const routes = [
{path:'/home',component:Home},
{path:'/user',component:User}
]
//4.创建一个路由实例
const router = new VueRouter({
routes:routes
})
//5.把路由挂到vue实例上
new Vue({
el:'.box',
router:router
})
</script>
路由的嵌套
<!-- 写路由的五个步骤:-->
<div class="box">
<!-- 1.写入链接标签和盛放标签-->
<router-link to='/home'>首页</router-link>
<router-link to='/user'>用户页</router-link>
<!--盛放每个页面对应的内容:-->
<router-view></router-view>
</div>
<!-- 导入js的顺序不能改变-->
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
<script>
//2.创建路由
var Home = {
template:`
<h1>这是首页</h1>
`
}
var User = {
template:`
<div class="box">
<h1>这是用户页</h1>
<ul>
<router-link to='/user/a'>登录</router-link>
<router-link to='/user/b'>注册</router-link>
</ul>
<router-view></router-view>
</div>
`
}
var A = {
template:`
<h1>这是登录</h1>
`
}
var B = {
template:`
<h1>这是注册</h1>
`
}
//3.配置路由
const routes = [
{path:'/home',component:Home},
{
path:'/user',
component:User,
children:[
{path:'a',component:A},
{path:'b',component:B}
]
}
]
//4.创建一个路由实例
const router = new VueRouter({
routes:routes
})
//5.把路由挂到vue实例上
new Vue({
el:'.box',
router:router
})
</script>
路由的传参
<!-- 1.查询字符串
/user/a?name=lucky&age=5
2.rest风格
/user/b/Tom/18-->
<!-- 写路由的五个步骤:-->
<div class="box">
<!-- 1.写入链接标签和盛放标签-->
<router-link to='/home'>首页</router-link>
<router-link to='/user'>用户页</router-link>
<!--盛放每个页面对应的内容:-->
<router-view></router-view>
</div>
<!-- 导入js的顺序不能改变-->
<script src="js/vue.js"></script>
<script src="js/vue-router.js"></script>
<script>
//2.创建路由
var Home = {
template:`
<h1>这是首页</h1>
`
}
var User = {
template:`
<div class="box">
<h1>这是用户页</h1>
<ul>
<router-link to='/user/a?name=lucky&age=5'>登录</router-link>
<router-link to='/user/b/Tom/18'>注册</router-link>
</ul>
<router-view></router-view>
</div>
`
}
var A = {
template:`
<div>
<h1>{{$route.query}}</h1>
<ul>
<li>{{$route.query.name}}</li>
<li>{{$route.query.age}}</li>
</ul>
</div>
`
}
var B = {
template:`
<div>
<h1>{{$route.params}}</h1>
<ul>
<li>{{$route.params.pname}}</li>
<li>{{$route.params.page}}</li>
</ul>
</div>
`
}
//3.配置路由
const routes = [
{path:'/home',component:Home},
{
path:'/user',
component:User,
children:[
{path:'a',component:A},
{path:'b/:pname/:page',component:B}
]
}
]
//4.创建一个路由实例
const router = new VueRouter({
routes:routes
})
//5.把路由挂到vue实例上
new Vue({
el:'.box',
router:router
})