Vue路由嵌套
注意 通过children 配置的 path 中的路由地址 不能加 / 开头。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./lib/vue-2.4.0.js"></script>
<script src="./lib/vue-router3.0.1.js"></script>
</head>
<body>
<div id="app">
<h1>客户中心</h1>
<router-link to="/login">登录</router-link>
<router-link to="/register">注册</router-link>
<router-view></router-view>
</div>
<template id='lc'>
<div>
<h2>登录模块</h2>
<router-link to="/login/newc">新用户</router-link>
<router-link to="/login/oldc">老用户</router-link>
<router-view></router-view>
</div>
</template>
<script>
var login = {
template: "#lc"
}
var register = {
template: "<h2>注册模块</h2>"
}
var newc = {
template: "<h2>新用户登录</h2>"
}
var oldc = {
template: "<h2>老用户登录</h2>"
}
// 获取 VueRouter 对象
var routerObj = new VueRouter({
routes : [
{path: "/" , redirect: "/login"},
{
path: "/login" ,
component: login,
children :[
{path: "newc" , component: newc},
{path: "oldc" , component: oldc}
]
},
{path: "/register" , component: register}
]
})
var vm = new Vue({
el: "#app",
data: { },
methods: { },
router: routerObj
})
</script>
</body>
</html>
路由案例
关键点:
- 路由匹配的时候如果有多个 组件模块 我们需要通过 components 来处理
- 同时在现在组件的时候,每个 组件 对应一个 router-view 标签,且通过 name属性来绑定,如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./lib/vue-2.4.0.js"></script>
<script src="./lib/vue-router3.0.1.js"></script>
<style>
html,
body {
margin: 0;
padding: 0;
}
.top {
background-color: orange;
height: 80px;
}
h1 {
margin: 0;
padding: 0;
font-size: 16px;
}
.container {
display: flex;
height: 600px;
}
.left {
background-color: lightgreen;
flex: 2;
}
.content {
background-color: lightpink;
flex: 8;
}
</style>
</head>
<body>
<div id="app">
<router-view name="topbox"></router-view>
<div class="container">
<router-view name="left"></router-view>
<router-view name="content"></router-view>
</div>
</div>
<script>
var topbox = {
template: "<h1 class='top'>头部局部</h1>"
}
var left = {
template: "<h1 class='left'>左侧菜单栏</h1>"
}
var content = {
template: "<h1 class='content'>内容主体</h1>"
}
var routerObj = new VueRouter({
routes: [{
path: "/",
components: {
"topbox": topbox,
"left": left,
"content": content
}
}]
})
var vm = new Vue({
el: "#app",
data: {},
methods: {},
router: routerObj
})
</script>
</body>
</html>