<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>64-VueRouter-嵌套路由</title>
<style>
*{
margin: 0;
padding: 0;
}
.onepage, .twopage{
width: 500px;
height: 500px;
}
.onepage{
background: pink;
}
.twopage{
background: skyblue;
}
.onesub1page, .onesub2page{
width: 100%;
height: 300px;
}
.onesub1page{
background: orangered;
}
.onesub2page{
background: blueviolet;
}
.nj-active{
background: skyblue;
}
</style>
<script src="js/vue.js"></script>
<!--1.导入Vue Router-->
<script src="js/vue-router.js"></script>
</head>
<body>
<!--
1.什么是嵌套路由?
嵌套路由也称之为子路由, 就是在被切换的组件中又切换其它子组件
例如: 在one界面中又有两个按钮, 通过这两个按钮进一步切换one中的内容
-->
<!--这里就是MVVM中的View-->
<div id="app">
<router-link to="/one" tag="button">切换到第一个界面</router-link>
<router-link to="/two" tag="button">切换到第二个界面</router-link>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
<template id="one">
<div class="onepage">
<p>我是第一个界面</p>
<router-link to="/one/onesub1" tag="button">切换到第一个子界面</router-link>
<router-link to="/one/onesub2" tag="button">切换到第二个子界面</router-link>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
</template>
<template id="onesub1">
<div class="onesub1page">
<p>我是第一个界面子界面1</p>
</div>
</template>
<template id="onesub2">
<div class="onesub2page">
<p>我是第一个界面子界面2</p>
</div>
</template>
<template id="two">
<div class="twopage">
<p>我是第二个界面</p>
</div>
</template>
<script>
// 1.定义组件
const onesub1 = {
template: "#onesub1",
};
const onesub2 = {
template: "#onesub2",
};
const one = {
template: "#one",
components:{
onesub1:onesub1,
onesub2: onesub2
}
};
const two = {
template: "#two"
};
// 2.定义切换的规则(定义路由规则)
const routes = [
// 数组中的每一个对象就是一条规则
{
path: '/one',
component: one,
children:[
{
// 注意点: 如果是嵌套路由(子路由), 那么不用写一级路径的地址, 并且也不用写/
path: "onesub1",
component: onesub1
},
{
// 注意点: 如果是嵌套路由(子路由), 那么不用写一级路径的地址, 并且也不用写/
path: "onesub2",
component: onesub2
}
]
},
// { path: '/one/onesub1', component: onesub1 },
// { path: '/one/onesub2', component: onesub2 },
{ path: '/two', component: two }
];
// 3.根据自定义的切换规则创建路由对象
const router = new VueRouter({
routes: routes,
linkActiveClass: "nj-active"
});
// 这里就是MVVM中的View Model
let vue = new Vue({
el: '#app',
// 4.将创建好的路由对象绑定到Vue实例上
router: router,
// 这里就是MVVM中的Model
data: {
},
// 专门用于存储监听事件回调函数
methods: {
},
// 专门用于定义计算属性的
computed: {
},
// 专门用于定义局部组件的
components: {
one: one,
two: two
}
});
// console.log(vue.$route);
</script>
</body>
</html>
Vue Router嵌套路由
最新推荐文章于 2024-06-20 15:58:49 发布