路由
2018-09-24 本文已影响0人
大宝贝_4c6e
1、什么是路由?
路由(vue-router):是Vue的一个核心插件,可以根据不同的url访问不同的页面,还可以创建单页面应用,又叫做SPA(SINGLE PAGE APPLICATION)应用。
2、router-link
<router-link>标签其实与html中的<a>标签相同,同样实现的是跳转的功能。
3、router-view
<router-view>标签是用来盛放链接对应的内容。
4、路由的跳转
例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>
.active{
color:red;
}
</style>
</head>
<body>
<div class="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>
var home={
template:`
<h1>这是首页</h1>
`
}
var user={
template:`
<h1>这是用户页</h1>
`
}
const routes=[
{path:"/",component:home},
{path:"/home",component:home},
{path:"/user",component:user}
]
const router = new VueRouter({
routes:routes,
linkActiveClass:"active"
})
new Vue({
el:".app",
router:router
})
</script>
</body>
</html>
运行结果为:
image.png image.png5、路由的嵌套
例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.active{
color:red;
}
</style>
</head>
<body>
<div class="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>
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>
`
}
const routes=[
{path:"/",component:home},
{path:"/home",component:home},
{
path:"/user",
component:user,
children:[
{path:'regist',component:Regist},
{path:'login',component:Login}
]
}
]
const router = new VueRouter({
routes:routes,
linkActiveClass:"active"
})
new Vue({
el:".app",
router:router
})
</script>
</body>
</html>
运行结果为:
image.pngimage.png image.png image.png