vue-router是vue.js官方的路由插件,它和vue.js是深度集成的,适合用于构建单页面应用。vue的单页面应用是基于路由和组件的,路由用于设定访问路径,并将路径和组件映射起来。传统的页面应用,是用一些超链接来实现页面切换和跳转的。在vue-router单页面应用中,则是路径之间的切换,也就是组件的切换。
注意:vue-router 2只适用于Vue2.x版本,下面我们是基于vue2.0讲的如何使用vue-router 2实现路由功能。
推荐使用npm安装。
npm install vue-router
登录后复制
一、使用路由
在main.js中,需要明确安装路由功能:
立即学习“前端免费学习笔记(深入)”;
import Vue from 'vue'import VueRouter from 'vue-router'import App from './App.vue'Vue.use(VueRouter)
登录后复制
1.定义组件,这里使用从其他文件import进来
import index from './components/index.vue'import hello from './components/hello.vue'
登录后复制
2.定义路由
const routes = [ { path: '/index', component: index }, { path: '/hello', component: hello },]
登录后复制
3.创建 router 实例,然后传 routes 配置
const router = new VueRouter({ routes})
登录后复制
4.创建和挂载根实例。通过 router 配置参数注入路由,从而让整个应用都有路由功能
const app = new Vue({ router, render: h => h(App)}).$mount('#app')
登录后复制
经过上面的配置之后呢,路由匹配到的组件将会渲染到App.vue里的
那么这个App.vue里应该这样写:
登录后复制
index.html里呢要这样写:
登录后复制
这样就会把渲染出来的页面挂载到这个id为app的p里了。
二、重定向 redirect
const routes = [ { path: '/', redirect: '/index'}, // 这样进/ 就会跳转到/index { path: '/index', component: index }]
登录后复制
三、嵌套路由
const routes = [ { path: '/index', component: index, children: [ { path: 'info', component: info} ] }]
登录后复制
通过/index/info就可以访问到info组件了
四、懒加载
const routes = [ { path: '/index', component: resolve => require(['./index.vue'], resolve) }, { path: '/hello', component: resolve => require(['./hello.vue'], resolve) },]
登录后复制
通过懒加载就不会一次性把所有组件都加载进来,而是当你访问到那个组件的时候才会加载那一个。对于组件比较多的应用会提高首次加载速度。
五、
在vue-router 1中,使用的是
在vue-router 2中,使用了替换1版本中的a标签
HomeHomeHomeHomeHomeUserRegister
登录后复制
六、路由信息对象
1.$route.path
字符串,对应当前路由的路径,总是解析为绝对路径,如 “/foo/bar”。
2.$route.params
一个 key/value 对象,包含了 动态片段 和 全匹配片段,如果没有路由参数,就是一个空对象。
3.$route.query
一个 key/value 对象,表示 URL 查询参数。例如,对于路径 /foo?user=1,则有 $route.query.user == 1,如果没有查询参数,则是个空对象。
4.$route.hash
当前路由的 hash 值 (不带 #) ,如果没有 hash 值,则为空字符串。
5.$route.fullPath
完成解析后的 URL,包含查询参数和 hash 的完整路径。
6.$route.matched
一个数组,包含当前路由的所有嵌套路径片段的 路由记录 。路由记录就是 routes 配置数组中的对象副本(还有在 children 数组)。
综合上述,一个包含重定向、嵌套路由、懒加载的main.js如下:
import Vue from 'vue'import VueRouter from 'vue-router'import App from './App'Vue.use(VueRouter)const router = new VueRouter({ routes:[ { path: '/', redirect: '/index' }, { path: '/index', component: resolve => require(['./components/index.vue'], resolve), children:[ { path: 'info', component: resolve => require(['./components/info.vue'], resolve) } ] }, { path: '/hello', component: resolve => require(['./components/hello.vue'], resolve) }, ]})const app = new Vue({ router, render: h => h(App)}).$mount('#app')
登录后复制
相关推荐:
实例详解thinkphp5 URL和路由功能
Node.js自定义实现文件路由功能的方法
nodeJS实现路由功能实例详解
以上就是Vue-Router2实现路由功能实例讲解的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2790526.html