这是我参与11月更文挑战的第3天,活动详情查看:2021最后一次更文挑战
什么是Router
Router是vue.js的官方路由管理器。
这是官方的教程:https://router.vuejs.org/zh/installation.html。
这可以轻松帮我们构建单页面应用页面之间的跳转。
怎么使用Router
- 引入router
首先在当前项目目录下进行npm install vue-router,如图安装成功
然后在main.js文件里import,即路由引入成功,然后使用use注册全局,最后实例route对象,挂载到vue实例上
import Vue from 'vue'
import App from './App.vue'
import VueRouter from 'vue-router'
Vue.config.productionTip = false
Vue.use(VueRouter)//每个路由应该映射一个组件,path代表浏览器上访问的路径,component代表组件
const routes = [ { path: '/', component: HelloWorld },]// 创建 router 实例,然后传 `routes` 配置// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new VueRouter({
routes // (缩写) 相当于 routes: routes
}
)
new Vue({
route,
render: h => h(App),}
).$mount('#app')
此时修改App.vue文件如下,这时候访问将会路径‘/’,将会把helloword渲染出来
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
<!-- <HelloWorld msg="这是我参与11月更文挑战的第1天"/>-->
</div>
</template>
接着我们继续定义另外2个组件,并加入到路由中
const routes = [
{ path: '/', component: HelloWorld },
{ path: '/user1', component: user1 },
{ path: '/user2', component: user2},]
如上所示,定义了2个path,分别访问的是user1组件和user2组件
http://localhost:8080/#/user1 这就会访问到user1组件
http://localhost:8080/#/user2这就会访问到user2组件
如果我们需要从一个组件跳到另一个组件,则需要使用push方法
例如 this.$router.push('/user1') 会跳转到user1组件页面
- router传参方式
共有2种方式传递参数
1.this.$router.push({path:'/user1',query:{id:'456'}})
2.this.$router.push({ name: 'user2', params: { id: '123' }})
注意2种方式区别
第一种跳转user1路由会在url路径上显示,如下
http://localhost:8080/#/user1?id=456
第二种方式 则需要在路由声明那里 多加一个name,并且跳转不会在url上显示参数
{ path: '/user2', name:'user2',component: user2}
在对应组件页面则可以使用下面方式获取
this.$route.query.id
this.$route.params.id
-
router重定向方式
{ path: '/', component: HelloWorld, redirect: '/user1' },
如上在路由对象里定义redirect,即为访问 ‘/’ 则会重定向到 'user1'
- router嵌套路由
声明如下,增加了一个children字段,里面就放对应的路由对象,可以一直往下嵌套
{ path: '/user2',
name:'user2',
component: user2,
children: [
{ path: 'user22', name: 'user22', component: user22, },
]
}
访问就是/user2/user22 就能访问到user22组件了
http://localhost:8080/#/user2/user22
- router路由的2种模式
简单介绍如下,一般用hash就可以了,如果需要好看点,没有#就用history,不过这个得后台服务器配合
const router = new VueRouter(
{ mode: "hash",
routes // (缩写) 相当于 routes: routes
})
1:hash模式(vue-router默认模式URL后面带#)使用URL的hash值来作为路由,支持所有浏览器
缺点:只能改变#后面的来实现路由跳转。
2:history模式(通过mode: 'history'来改变为history模式)HTML5 (BOM)History API 和服务器配置
缺点:怕刷新如果后端没有处理这个情况的时候前端刷新就是实实在在的请求服务器这样消耗的时间很多还很慢。
总结
router路由极大方便了我们vue项目开发,还有很多router的使用技巧暂时没有列出来,后续会继续补充。
路由拦截、路由的跳转动画等等一些也都是我们需要注意的地方。路由拦截这一块后面在单独研究写一篇。