vue路由-router
- 路由配置文件书写模板:
1// 1.引入vue
2import vue from 'vue'
3// 2.引入VueRouter
4import VueRouter from 'vue-router'
5
6import Home from "../views/Home"
7import About from "../views/About"
8import demo from "../views/demo"
9
10// 3.使用VueRouter
11vue.use(VueRouter)
12
13// 4.new 一个VueRouter对象赋值给一个常量
14const r = new VueRouter({
15
16 // 5.设置 路由方式
17 mode: 'history',
18
19 // 6.在routers数组中写各种路由
20 routes: [{
21 // 7.在路由中写明路径和对应显示的组件
22 path: "/",
23 component: Home
24 },
25 {
26 path: "/about",
27 component: About
28 },
29 {
30 path: "/demo",
31 component: demo
32 }
33 ]
34})
35// 8.将VueRouter开放出去
36export default r
路由之间切换
在路由配置文件中,定义好路径和组件名。App.vue中使用
路由传值的三种方式
第一种
- App.vue中定义:
1export default {
2 data() {
3 return {
4 str: "yy",
5 };
6 },
7 methods: {
8 fun() {
9 this.$router.push("/demo?name=" + this.str);
10 },
- 页面取值
1<template>
2 <div>
3 <h1>我是demo</h1>
4 <p>第一种方式获取的数值为:{{ this.$route.query.name }}</p>
5 </div>
6</template>
第二种
- App.vue中定义
1 fun2() {
2 this.$router.push({
3 path: "/demo2",
4 query: {
5 name: this.str,
6 },
7 });
8 },
- 页面调用
1<template>
2 <div>
3 <h1>demo2</h1>
4 <p>第二种方式获取的数值为:{{ this.$route.query.name }}</p>
5 </div>
6</template>
第三种
1 fun3() {
2 this.$router.push("/demo3/123");
3 },
使用此种方法要注意修改对应的key键
1{
2 path: '/demo3/:id',
3 component: demo3
4 },
- 调用
1 <p>第三种方法获取的数值为:{{ $route.params.id }}</p>
组件模块懒加载
1import vue from 'vue'
2import VueRouter from 'vue-router'
3vue.use(VueRouter)
4const r = new VueRouter({
5 mode: 'history',
6 routes: [
7 {
8
9 path: "/xueyuan/wuliu",
10 component: () => import("../views/xueyuan/wuliu.vue"),
11 children: [
12 {
13 path: '/xueyuan/wuliu/',
14 component: () => import("../views/wuliu/class01.vue")
15 },
16 {
17 // ------------------------------------------------------------------------------------------------
18 path: '/xueyuan/wuliu/chass02',
19 // 1.我们可以用图片懒加载的方式(箭头函数的方式)来代替import引入的方式
20 component: () => import("../views/wuliu/class02.vue")
21 },
22 {
23 path: '/xueyuan/wuliu/chass03',
24 // 2.在文件路径之前加入 加入自定义命名的方式,可修改文件名,具体看图
25 component: () => import(/*webpackChunkName:"xueyuanWuliuChass03"*/"../views/wuliu/class03.vue")
26 },
27 // -----------------------------------------------------------------------------------------------
28
29 ]
30
31 },
32 {
33
34 path: "/xueyuan/it",
35 component: () => import("../views/xueyuan/it.vue"),
36 children: [
37 {
38 path: '/xueyuan/it/',
39 component: () => import("../views/it/class01.vue")
40 },
41 {
42 path: '/xueyuan/it/chass02',
43 component: () => import("../views/it/class02.vue")
44 },
45 {
46 path: '/xueyuan/it/chass03',
47 component: () => import("../views/it/class03.vue")
48 },
49 ]
50
51 },
52 ]
53})
54
55export default r
56const originalPush = VueRouter.prototype.push
57VueRouter.prototype.push = function push(location) {
58 return originalPush.call(this, location).catch(err => err)
59}