目录

一.使用路由

1.1配置路由

1.2采用路由

二.路由懒加载

三.路由重定向

四.嵌套路由

五.路由跳转

1.1标签式

1.2编程式

1.3路由的query参数

1.4命名路由

1.5路由的 params 参数

1.6 路由的 props 配置

六.路由守卫

1.0简介:

1.1全局前置守卫(beforeEach)

1.2全局后置守卫(afterEach,少用)

1.3独享守卫(beforeEnter)略

1.4组件内部守卫(beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave)略


前言:

vue 属于单页面应用,所谓的路由,就是根据浏览器路径不同,用不同的视图组件替换这个页面内容展示

一.使用路由

1.1配置路由

新建一个路由index.js 文件,建立【路径】与【视图组件】之间的映射关系

import Vue from 'vue'
import VueRouter from 'vue-router'
import ContainerView from '@/views/example/ContainerView.vue'
import LoginView from '@/views/example/LoginView.vue'
import NotFoundView from '@/views/example/NotFoundView.vue'Vue.use(VueRouter)const routes = [{path:'/',component: ContainerView},{path:'/login',component: LoginView},{path:'/404',component: NotFoundView}
]const router = new VueRouter({routes
})export default router

注:@代表src下

1.2采用路由

在 main.js 中采用我们的路由 js,其实在引入时可以省略index,因为index是个特殊的东西,默认找不到就找index

import Vue from 'vue'
import App from './views/App.vue'
import router from './router/index'//引入路由
import store from './store'
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'Vue.config.productionTip = falseVue.use(Element)
new Vue({router,store,render: h => h(App)
}).$mount('#app')

根组件是App.vue,内容为:

<template><div class="all"><router-view></router-view></div>
</template>

<router-view> 起到占位作用,改变路径后,这个路径对应的视图组件就会占据 <router-view> 的位置,替换掉它之前的内容

二.路由懒加载

import Vue from 'vue'
import VueRouter from 'vue-router'Vue.use(VueRouter)const routes = [{path:'/',component: () => import('@/views/example/ContainerView.vue')},{path:'/login',component: () => import('@/views/example/LoginView.vue')},{path:'/404',component: () => import('@/views/example/NotFoundView.vue')}
]const router = new VueRouter({routes
})export default router
  • 静态导入是将所有组件的 js 代码打包到一起,如果组件非常多,打包后的 js 文件会很大,影响页面加载速度

  • 动态导入是将组件的 js 代码放入独立的文件,用到时才加载

三.路由重定向

const routes = [{path:'/404',component: () => import('@/views/example/NotFoundView.vue')},{path:'*',redirect: '/404'}]

①redirect 可以用来重定向(跳转)到一个新的地址

②path 的取值为 * 表示匹配不到其它 path 时,就会匹配它

四.嵌套路由

比如当我们进入主页之后有分类,然后当选择其中一个分类之后进入对应的详情,这个时候组件内再要切换内容,就需要用到嵌套路由(子路由) ;官方文档中给我们提供了一个children属性这个属性是一个数组类型,里面实际放着一组路由;这个时候父子关系结构就出来了,所以children属性里面的是路由相对来说是children属性外部路由的子路由;

const routes = [{path:'/',component: () => import('@/views/example/ContainerView.vue'),redirect: '/c/p1',children: [{ path:'c/p1',component: () => import('@/views/example/container/P1View.vue')},{ path:'c/p2',component: () => import('@/views/example/container/P2View.vue')},{ path:'c/p3',component: () => import('@/views/example/container/P3View.vue')}]},{path:'/login',component: () => import('@/views/example/LoginView.vue')},{path:'/404',component: () => import('@/views/example/NotFoundView.vue')},{path:'*',redirect: '/404'}
]

子路由变化,切换的是 ContainerView 组件 中 <router-view></router-view> 部分的内容

<template><div class="container">//路由占位标签<router-view></router-view></div>
</template>

五.路由跳转

1.1标签式

container组件内:

<template><div class="container"><el-container><el-aside width="200px"><router-link to="/c1/p1">P1</router-link><router-link to="/c1/p2">P2</router-link><router-link to="/c1/p3">P3</router-link> </el-container></div>
</template>
<script>export default options;
</script>

标签导航<router-link>,<router-link>是通过转义为<a></a>标签进行跳转,其中router-link标签中的to属性会被转义为a标签中的href属性;

router-link属性介绍:

  • to:用于指定跳转的路径
  • tag:tag可以指定<router-link>之后渲染成什么组件,比如我们下面的代码会被渲染成一个<li>元素,而不是<a> 。 如:<router-link to='/home' tag='li'>
  • replace:replace不会留下history记录,所以指定replace的情况下,后退键返回不能返回到上一个页面中
  • active-class:当<router-link>对应的路由匹配成功时,会自动给当前元素设置一个router-link-active的class,设置active-class可以修改默认的名称。

1.2编程式

container组件内:

<template><div class="container"><el-header><el-button type="primary" icon="el-icon-edit" circle size="mini" @click="jump('/c1/p1')"></el-button><el-button type="success" icon="el-icon-check" circle size="mini" @click="jump('/c1/p2')"></el-button><el-button type="warning" icon="el-icon-star-off" circle size="mini" @click="jump('/c1/p3')"></el-button></el-header></div>
</template>
<script>
const options = {methods : {jump(url) {// this.$router拿到的是路由对象this.$router.push(url);//跳转路由}}
}
export default options;
</script>
  • 其中 this.$router 是拿到路由对象

  • push 方法根据 url 进行跳转

补充:

1.3路由的query参数

①传递参数

<!-- 跳转并携带query参数,to的字符串写法 -->
<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">跳转</router-link><!-- 跳转并携带query参数,to的对象写法(推荐) -->
<router-link :to="{path:'/home/message/detail',query:{id: m.id,title: m.title}}"
>跳转</router-link>

②接收参数

$route.query.id
$route.query.title

实例如下:

src/router.index.js

import VueRouter from "vue-router";
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'routes:[{path:'/about',component:About},{path:'/home',component:Home,children:[{path:'news',component:News},{path:'message',component:Message,children:[{path:'detail',component:Detail}]}]}]
})

src/pages/Message.vue

<template><div><ul><li v-for="m in messageList" :key="m.id"><!-- 跳转路由并携带query参数,to的字符串写法 --><!-- <router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp; --><!-- 跳转路由并携带query参数,to的对象写法 --><router-link :to="{path:'/home/message/detail',query:{}}">{{m.title}}</router-link>&nbsp;&nbsp;</li></ul><hr/><router-view></router-view></div>
</template>
<script>export default {name:'News',data(){return{messageList:[{id:'001',title:'消息001'},{id:'002',title:'消息002'},{id:'003',title:'消息003'}]}}}
</script>

src/pages/Detail.vue

<template><ul><li>消息编号:{{ $route.query.id }}</li><li>消息标题:{{ $route.query.title }}</li></ul>
</template>
<script>export default {name:'Detail'}
</script>

1.4命名路由

作用:可以简化路由的跳转

使用:

①给路由命名

{path:'/demo',component:Demo,children:[{path:'test',component:Test,children:[{name:'hello' // 给路由命名path:'welcome',component:Hello,}]}]
}

②通过name属性简化跳转

<!--简化前,需要写完整的路径 -->
<router-link to="/demo/test/welcome">跳转</router-link>
<!--简化后,直接通过名字跳转 -->
<router-link :to="{name:'hello'}">跳转</router-link>
<!--简化写法配合传递参数 -->
<router-link :to="{name:'hello',query:{id:666,title:'你好'}}"
>跳转</router-link>

1.5路由的 params 参数

①配置路由,声明接收params参数

{path:'/home',component:Home,children:[{path:'news',component:News},{component:Message,children:[{name:'xiangqing',path:'detail/:id/:title', // 使用占位符声明接收params参数component:Detail}]}]
}

②传递参数

特别注意:路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!

<!-- 跳转并携带params参数,to的字符串写法 -->
<router-link :to="/home/message/detail/666/你好">跳转</router-link><!-- 跳转并携带params参数,to的对象写法 -->
<router-link :to="{name:'xiangqing',params:{id:666,title:'你好'}}"
>跳转</router-link>

③接收参数

$route.params.id$route.params.title

实例如下:

src/router/index.js

import VueRouter from "vue-router";
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
export default new VueRouter({routes:[{path:'/about',component:About},{path:'/home',component:Home,children:[{path:'news',component:News},{path:'message',component:Message,children:[{name:'xiangqing',path:'detail/:id/:title',   // 使用占位符声明接收params参数component:Detail}]}]}]
})

src/pages/Message.vue

<template><div><ul><li v-for="m in messageList" :key="m.id"><!-- 跳转路由并携带params参数,to的字符串写法 --><!-- <router-link :to="`/home/message/detail/${m.id}/${m.title}`">{{m.title}}</router-link>&nbsp;&nbsp; --><!-- 跳转路由并携带params参数,to的对象写法 --><router-link :to="{title:m.title}}">{{m.title}}</router-link>&nbsp;&nbsp;</li></ul><hr/><router-view></router-view></div>
</template>
<script>export default {name:'News',data(){return{messageList:[{id:'001',title:'消息001'},{id:'002',title:'消息002'},{id:'003',title:'消息003'}]}}}
</script>

src/pages/Detail.vue

<template><ul><li>消息编号:{{ $route.params.id }}</li><li>消息标题:{{ $route.params.title }}</li></ul>
</template>
<script>export default {name:'Detail'}
</script>

1.6 路由的 props 配置

props作用:让路由组件更方便的收到参数

{name:'xiangqing',path:'detail/:id',component:Detail,//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件// props:{a:900}//第二种写法:props值为布尔值,为true时,则把路由收到的所有params参数通过props传给Detail组件// props:true//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件props($route){return {id: $route.query.id,title: $route.query.title}}
}

src/router/index.js

import VueRouter from "vue-router";
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'
export default new VueRouter({routes:[{path: '/about',component: About},{path:'/home',component:Home,children:[{path:'news',component:News},{path:'message',component:Message,children:[{name:'xiangqing',path:'detail/:id/:title',// props:{a:1,b:'hello'}// props的第二种写法,值为布尔值,// 若布尔值为真,会把该路由组件收到的所有params参数,以props的形式传给Detail组件// props:true// props的第三种写法,值为函数props(params) { // 这里可以使用解构赋值return {id: params.id,title: params.title,}}}]}]}]
})

src/pages/Detail.vue

<template><ul><li>消息编号:{{ id }}</li><li>消息标题:{{ title }}</li></ul>
</template>
<script>export default {name:'Detail',props:['id','title']}
</script>

六.路由守卫

1.0简介:

路由守卫就是路由跳转的一些验证,比如登录鉴权(没有登录不能进入个人中心页)等等等

1.1全局前置守卫(beforeEach)

to: 要进入的目标路由(去哪儿)

from: 要离开的路由(从哪来)

next 是否进行下一步(要不要继续),写next()相当于 next(true) 继续执行;不写,相当于 next(false)终止执行。next(path)跳转 例如next("/login")

给需要守卫的路(需要权限验证的路由)由加上: meta: { permission: true },

router.beforeEach((to, from, next) => {if (to.meta.permission) {if (sessionStorage.getItem("token")) {next();} else {alert("请先登录");next("/login");}} else {next();}
});

1.2全局后置守卫(afterEach,少用)

router.afterEach((to, from) => {// to and from are both route objects.
});

1.3独享守卫(beforeEnter)

1.4组件内部守卫(beforeRouteEnterbeforeRouteUpdatebeforeRouteLeave)

Vue-Router学习记录相关推荐

  1. 【VUE】学习记录一

    [VUE]学习记录 学习视频为:尚硅谷Vue2.0+Vue3.0全套教程丨vuejs从入门到精通 1.查询vue知识点: https://v2.cn.vuejs.org/ 2. 下载和引入 2.1 下 ...

  2. 安装vue Devtools学习记录

    在学习vue之前,建议使用Google chrome上安装vue devtools拓展工具.vue devtools提供界面供我们查看vue组件和全局状态管理器vuex中记录的数据. 有条件的可以直接 ...

  3. vue基础学习记录(一)

    根据B站黑马程序员 VUE教程基础学习 为了毕业设计做准备 Vue基础 工具准备 Vue的基本使用步骤 vue模板语法 `v-cloak`指令用法 数据绑定指令 数据响应式 双向数据绑定 MVVM设计 ...

  4. 基于VueAxios制作音乐播放器(bilibili黑马程序员Vue入门学习记录)

    目录 使用Vue制作一个音乐播放器 前言 Vue Vue导入 Vue挂载 Vue指令 v-text v-html v-on v-show v-if v-bind v-for v-model axios ...

  5. vue基础学习记录(三)

    一.生命周期(钩子函数) 实例生命周期钩子 new Vue ({beforeCreate:function(){alert("组件实例化之前执行的函数");},created:fu ...

  6. VUE+ElementUi学习记录(一)tabs切换导致页面比例不自适应,包含echarts

    问题 element-ui中使用tab切换v-chart,实现自适应布局 解决方案 根本原因,elementui的tab标签切换使用的是display:none; display:none; 这就导致 ...

  7. (50)Vue Router插件介绍

    一.Vue Router插件介绍 Vue Router 是 Vue.js 的官方插件,用来快速实现单页应用. 二.Vue Router学习内容 • 单页应用 • 前端路由 • Vue Router 三 ...

  8. Vue学习记录 (ref,生命周期,组件,router)

    ref="名称":注册引用信息 this.$ref.名称:获取对象(此为操作dom节点) 计算属性:computed 在差值表达式中调用此函数会直接返回计算结果,而不是函数本身 当 ...

  9. Vue.js 入门 :去哪儿网APP案例 学习记录

    推荐博客 Vue 2.5 开发 去哪儿 旅游网站项目记录 项目源码 : https://gitee.com/doublesgzl/Travel 第六章 项目实战 6-1 环境配置 (建议看下视频) 6 ...

  10. Vue学习笔记(六)--- 前端路由 Vue Router

    一.路由 1.概念 ​ 路由本质上来说就是一种对应关系,比如说我们在浏览器中输入不同的 url 地址,我们就能访问不同的资源,那么这 url 地址与资源之间的对应关系,就是路由. 2.分类 ① 后端路 ...

最新文章

  1. 团队冲刺站立会议07
  2. 微信公众平台开发(38)一站到底在线答题
  3. opencv-api minAreaRect
  4. python网络爬虫学习笔记(一):网页基础
  5. WindowsXP下搭建GIT服务器
  6. 简单介绍三级分销系统开发源码
  7. 数仓OLAP基础知识
  8. 3.2nbsp;系统分析之正反馈
  9. pythonbmi代码_用python写一个BMI体制指数测试
  10. 使用windows自带虚拟机---Hyper-V 管理器
  11. 华为的芯片战略:别忘记,代号—SD502!
  12. 360°全景影像移动端类库--PanoramaGL
  13. 卓越电脑定时关机软件
  14. node restify框架使用openai(chatgpt)接口
  15. UART(Universal Asynchronous Receiver/Transmitter,异步收发传输器)
  16. 转: 云计算openstack—云计算、大数据、人工智能
  17. CAD软件中怎么批量导入导出坐标数据?
  18. icmp端口_icmptunnel搭建icmp隧道——超详细步骤
  19. 【✨十五天搞定电工基础】一阶电路的暂态分析
  20. 人工智能数据集(资源篇)(更新于2020.11.27)

热门文章

  1. 53所高校研究生补贴一览表
  2. 20201104大模拟(一)
  3. 【工具】Vscode翻译插件推荐(不用谷歌翻译api、支持短句英汉互译、支持查词、支持自动补全、不需要浏览器)
  4. SolidWorks_画螺杆
  5. 【BZOJ】4292: [PA2015]Równanie
  6. yolov3代码详解(七)
  7. html转换成canvas一片空白,html2canvas截图空白问题怎么解决 html2canvas截图空白问题解决方法...
  8. 关于swiper在移动端,快速上下滑动出现白边的解决办法
  9. Unity Steam_VR开发工具插件---VRTK 自带案例分析
  10. Oracle增加修改删除字段