今天小编给大家分享一下vue-router里怎么使用嵌套路由的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
模板抽离
我们已经学习过了Vue模板的另外定义形式,使用<template></template>。
<!-- 模板抽离出来 --> <template id="home"> <div>首页</div> </template> <template id="news"> <div>新闻</div> </template>
然后js里定义路由组件的时候:
// 1. 定义(路由)组件。 const Home = { template: '#home' }; const News = { template: '#news' };
路由嵌套
实际应用界面,通常由多层嵌套的组件组合而成。
比如,我们 “首页”组件中,还嵌套着 “登录”和 “注册”组件,那么URL对应就是/home/login和/home/reg。
<template id="home"> <!-- 注意:组件只能有一个根元素,所以我们包装到这个div中 --> <div> <h3>首页</h3> <router-link to="/home/login">登录</router-link> <router-link to="/home/reg">注册</router-link> <!-- 路由匹配到的组件将渲染在这里 --> <router-view></router-view> </div> </template>
这是访问/home后的模板,其中我们需要把/home/login和/home/reg渲染进来。
<template id="login"> <div>登录界面</div> </template> <template id="reg"> <div>注册界面</div> </template>
//定义路由组件 const Login = { template: '#login' }; const Reg = { template: '#reg' };
3.定义路由
// 2. 定义路由 const routes = [ { path: '/', redirect: '/home' }, { path: '/home', component: Home, children:[ { path: '/home/login', component: Login}, { path: '/home/reg', component: Reg} ] }, { path: '/news', component: News} ]
注意我们在home路由配置了它的children。这就是嵌套路由。
4.案例全部代码如下:
<!DOCTYPE html> <html> <head> <title></title> <Meta charset="utf-8"> <script src="http://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> </head> <body> <div id="Box"> <p> <router-link to="/home">home</router-link> <router-link to="/news">news</router-link> </p> <router-view></router-view> </div> <!-- 模板抽离出来 --> <template id="home"> <!-- 注意:组件只能有一个根元素,所以我们包装到这个div中 --> <div> <h3>首页</h3> <router-link to="/home/login">登录</router-link> <router-link to="/home/reg">注册</router-link> <!-- 路由匹配到的组件将渲染在这里 --> <router-view></router-view> </div> </template> <template id="news"> <div>新闻</div> </template> <template id="login"> <div>登录界面</div> </template> <template id="reg"> <div>注册界面</div> </template> <script type="text/javascript"> // 1. 定义(路由)组件。 const Home = { template: '#home' }; const News = { template: '#news' }; const Login = { template: '#login' }; const Reg = { template: '#reg' }; // 2. 定义路由 const routes = [ { path: '/', redirect: '/home' }, { path: '/home', component: Home, children:[ { path: '/home/login', component: Login}, { path: '/home/reg', component: Reg} ] }, { path: '/news', component: News} ] // 3. 创建 router 实例,然后传 `routes` 配置 const router = new VueRouter({ routes // (缩写)相当于 routes: routes }) // 4. 创建和挂载根实例。 // 记得要通过 router 配置参数注入路由, // 从而让整个应用都有路由功能 const app = new Vue({ router }).$mount('#Box') // 现在,应用已经启动了! </script> </body> </html>
Vue的优点
Vue具体轻量级框架、简单易学、双向数据绑定、组件化、数据和结构的分离、虚拟DOM、运行速度快等优势,Vue中页面使用的是局部刷新,不用每次跳转页面都要请求所有数据和dom,可以大大提升访问速度和用户体验。
以上就是“vue-router里怎么使用嵌套路由”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注编程之家行业资讯频道。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。