此代码中one为菜单一,two为菜单二,a为菜单1,b为菜单2,c为菜单3,d为菜单4;
要注意template中的内容必须写在一个div中,且 routes中的children里的path不能加斜杠
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.9/vue.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/vue-router/3.4.3/vue-router.min.js"></script>
<style>
*{
margin: 0px;
padding: 0px;
}
html,body,#app{
height: 100%;
width: 100%;
}
.left{
height: 100%;
width: 10%;
background-color: aquamarine;
float: left;
}
.right{
height: 100%;
width: 90%;
background-color: beige;
float: left;
}
</style>
</head>
<body>
<div id="app">
<div class="left">
<ul>
<li @click='toone'>菜单一</li>
<li @click='totwo'>菜单二</li>
</ul>
</div>
<div class="right">
<router-view></router-view>
</div>
</div>
<script>
let one={
template:`
<div>
<span @click='toa'>菜单1</span>
<span @click='tob'>菜单2</span>
<div style="height: 500px;background-color: lightblue;">
<router-view></router-view>
</div>
</div>
`,
methods:{
toa(){
this.$router.push('/one/a')
},
tob(){
this.$router.push('/one/b')
}
}
}
let a={
template:`
<div>这是菜单1</div>
`
}
let b={
template:`
<div>这是菜单2</div>
`
}
let two={
template:`
<div>
<span @click='toc'>菜单3</span>
<span @click='tod'>菜单4</span>
<div style="height: 500px;background-color: lightblue;">
<router-view></router-view>
</div>
</div>
`,
methods:{
toc(){
this.$router.push('/two/c')
},
tod(){
this.$router.push('/two/d')
}
}
}
let c={
template:`
<div>这是菜单3</div>
`
}
let d={
template:`
<div>这是菜单4</div>
`
}
let router = new VueRouter({
routes:[{
path:'/one',
component:one,
children:[{
path:'a',
component:a
},{
path:'b',
component:b
}]
},{
path:'/two',
component:two,
children:[{
path:'c',
component:c
},{
path:'d',
component:d
}]
}]
})
new Vue({
el:'#app',
router,
methods:{
toone(){
this.$router.push('/one')
},
totwo(){
this.$router.push('/two')
}
}
})
</script>
</body>
</html>
效果如下: