Vue-router路由

发布于:2024-10-13 ⋅ 阅读:(10) ⋅ 点赞:(0)

目录

16.1 介绍

16.2 vue的路由

16.3 安装路由模块

16.5 声明式路由

16.5.1 创建MyInfo.vue

16.5.1 创建Admin.vue

16.5.2 创建静态路由表

16.5.3 main.js引入路由模块并使用

16.5.4 App.vue使用路由

16.6 编程式路由

16.7 参数的传递

16.7.1 声明式路由传参

16.7.2 编程式路由传参

16.8 嵌套路由

16.9 其他


 

16.1 介绍

路由的本质就是一种对应关系,比如说我们在url地址中输入我们要访问的url地址之后,浏览器要去请求这个url地址对应的资源。

那么url地址和真实的资源之间就有一种对应的关系,就是路由。

路由分为前端路由后端路由

1)后端路由是由服务器端进行实现,并完成资源的分发(我们之前的项目)

2)前端路由是依靠hash值(锚链接)的变化进行实现 (vue官网就是使用这种)

前端路由的基本概念: 根据不同的事件来显示不同的页面内容,即事件与事件处理函数之间的对应关系 前端路由主要做的事情就是监听事件并分发执行事件处理函数

16.2 vue的路由

Vue默认属于单页面的程序,主要通过URL中的hash来实现不同页面之间的切换。这种切换方式称作前端路由。

Vue Router的核心作用

  • 跳转/切换页面

    • 声明式(写标签)

 <router-link to="要跳转的组件名称">
  • 编程式(写代码)

 this.$router.push("要跳转的组件名称")
  • 跳转携带数据

    • 编程式导航实现传递参数

      • 传递 this.$router.push({path:'路径',params:{参数名:值,...}})

      • 接收 this.$router.params.参数名

  • 路由模式

    • hash模式:监听浏览器地址hash值变化,执行相应的js切换网页;

    • history模式:利用history API实现url地址改变,网页内容改变;

    • 它们最明显的区别就是hash会在浏览器地址后面增加#号

16.3 安装路由模块

介绍 | Vue Router (vuejs.org)

npm install vue-router
# 如果报错,可能是npm版本过高,存在兼容性问题,那么使用如下命令
npm install --legacy-peer-deps vue-router@3.5.2
npm install --legacy-peer-deps vue-router@3.1.3

ps: 今天练习过一次以后,后续在创建项目时可以直接选择路由部分内容,创建出的项目直接就配置好了

16.5 声明式路由

需求:在主页与个人中心之间切换显示

16.5.1 创建MyInfo.vue

路由页面建议创建在src/views/下

<template>
  <div>
    <h1>个人中心</h1>
  </div>
</template>
​
<script>
export default {
  name: "MyInfo"
}
</script>
​
<style scoped>
​
</style>

16.5.1 创建Admin.vue

<template>
<div>
  <h1>主页</h1>
  <p>主页</p>
  <p>主页</p>
  <p>主页</p>
  <p>主页</p>
  <p>主页</p>
  <p>主页</p>
  <p>主页</p>
  <p>主页</p>
</div>
</template>
​
<script>
export default {
  name:'Admin'
}
</script>
​
<style scoped>
​
</style>

16.5.2 创建静态路由表

在/src下创建router文件夹,

在/src/router/创建index.js文件

填充以下内容

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '../components/HelloWorld'
import MyInfo from "../views/MyInfo";
​
Vue.use(Router)
// export是导出路由对象,只有在这里导出了,main.js文件头上面才能 import 导入
export default new Router({
    routes: [
        {
            path: '/', // 匹配<router-link to="">中的路径
            name: 'HelloWorld', // 这个name属性可写可不写
            component: HelloWorld // 要跳转的组件对象
        },
        {
            path: '/MyInfo',
            name: 'MyInfo',
            component: MyInfo
        }
    ],
    // mode: 'history'
    mode: 'hash'
})

16.5.3 main.js引入路由模块并使用

在main.js中引入路由模块并使用

import Vue from 'vue'
import App from './App'
import router from './router' //引入上一步导出的路由模块,并设置名字为router
Vue.config.productionTip = false
​
new Vue({
  render: h => h(App),
  // router:router  // 使用路由,可以简写为router
    router
}).$mount('#app')

16.5.4 App.vue使用路由

<template>
  <div id="app">
    <ul>
      <li>
        <!-- 
           <router-link>用于导航,其实就是a标签
           to表示要跳转的资源的路径
           tag 将router-link渲染成想要的原生标签,默认是a标签,可以改成button
        -->
        <router-link to="/" tag="button">首页</router-link>
      </li>
      <li>
        <router-link to="/MyInfo">个人信息</router-link>
      </li>
    </ul>
    <!-- router-view 路由填充位,要跳转的组件在此展示,位置任意 -->
    <router-view/>
  </div>
</template>
​
<script>
​
export default {
  name: 'App',
}
</script>
​
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

启动测试

练习完后可以重写创建vue项目,选择Router依赖,这样创建出的项目自带路由配置

16.6 编程式路由

刚才演示的是声明式路由,也可以使用编程式路由

演示: 主页与公共页面切换

创建公告页Note.vue

<template>
<div>
  <h1>公告页面</h1>
  <ol>
    <li>老杨不瞌睡了</li>
    <li>萌萌也+1</li>
    <li>相宇明天好好做操</li>
  </ol>
</div>
</template>
​
<script>
export default {
  name: "Note"
}
</script>
<style scoped>
</style>

src/router/index.js 设置路由规则

export default new Router({
    routes: [
        {
            path: '/',
            name: 'HelloWorld',
            component: HelloWorld
        },
        {
            path: '/MyInfo',
            name: 'MyInfo',
            component: MyInfo
        },
        {
            path: '/Note',
            name: 'Note',
            component: Note
        }
    ],
    // mode: 'history'
    mode: 'hash'
})

App.vue设置标签,绑定事件,事件触发函数,函数内编写代码实现路由

this.$router.push("/路径") --> <router-link to="/路径">

this.$router.push("/Note")
// 注意!!!!别写错,有个叫做this.$route

bug: 第一次点击跳转没事,再点一次报错

解决:

  • 方式1: 设置异常捕获

// 在router中的index.js中加上以下代码,注意加在use之前写
const routerPush = Router.prototype.push;
Router.prototype.push = function (location) {
    return routerPush.call(this, location).catch((err) => {});
};

方式2:

在编程式是路由,即this.$router.push() 修改成这样

const currentRoute = this.$router.currentRoute;
if (currentRoute.path !== '/Note') {
    this.$router.push({
        path:"/Note"
    })
}

16.7 参数的传递

16.7.1 声明式路由传参

演示App.vue中将数据传递给MyInfo.vue

在路由表中设参

export default new Router({
  routes: [
    ...
    {
      path:'/MyInfo/:id', //设参
      component:MyInfo
    }
  ]
})

在App.vue中传参

<template>
  <div id="app">
    <ul>
      <li>
        <router-link to="/" tag="button">首页</router-link>
      </li>
      <li>
        <!-- 跳转至MyInfo,并携带id 1001 -->  
        <router-link to="/MyInfo/1001">个人信息</router-link>
      </li>
    </ul>
    <!-- router-view 用于显示匹配的组件,类似显示路由到的组件的区域,位置任意 -->
    <router-view/>
  </div>
</template>
​
<script>
...
</script>
​
<style>
...
</style>

在MyInfo.vue中接参

<template>
  <div>
    <h1>个人信息</h1>
    <span>id-->{{id}}</span>
  </div>
</template>
​
<script>
export default {
  name: "EmployeeList",
  data:function(){
    return {
      id:this.$route.params.id // 注意是$route不是$router
    }
  }
}
</script>
<style scoped>
</style>

16.7.2 编程式路由传参

演示App.vue中将数据传递给Note.vue

App.vue的编程跳转js中设置要传递的数据

  methods:{
    toNote(){
      //this.$router.push("/Note")
      this.$router.push({path:"/Note",query:{username:'老王'}})
    }
  }

Note.vue中接收参数

<template>
<div>
  <h1>网站公告</h1>
  <span>id --> {{id}}</span>
</div>
</template>
​
<script>
export default {
  name: "Note",
  data:function(){
    return {
      id:this.$route.query.username  
        // 注意是query,因为是按照路径方式发送,注意查看浏览器url
    }
  }
}
</script>

ps: 后续也可以通过VueX来完成传递数据

16.8 嵌套路由

嵌套路由 | Vue Router (vuejs.org)

多层多级组件嵌套时的路由

例如:

需求: 在个人中心组件中,再设置三个链接,可以点击切换[头像|家庭信息|学校信息]

代码:

创建三个组件页面Touxiang.vue,Family.vue,School.vue

在MyInfo组件中设置路由链接发出请求路径,并且设置路由填充位

<template>
<div>
  <h1>个人中心</h1>
  <h3>id = {{id}}</h3>
<!--  /my/tx-->
<!--  /my/family-->
<!--  /my/school-->
  <router-link to="/my/tx">头像</router-link>|
  <router-link to="/my/family">家庭信息</router-link>|
  <router-link to="/my/school">学校信息</router-link>|
  <router-view></router-view>
</div>
</template>

在router/index.js中设置myinfo组件的子路由

        {
            path:'/my',
            name:'MyInfo',
            component:MyInfo,
            children:[
                // 子路径要与父类拼接成完整路径,此处不需要加/
                { path:'tx',component:Touxiang},
                { path:'family',component:Family},
                { path:'school',component:School},
            ]
        },

如果有路径中有数据的话,子组件一样可以取值

<!--  MyInfo.Vue-->
<template>
<div>
  <h1>个人中心</h1>
  <h3>id = {{id}}</h3>
<!--  /my/tx-->
<!--  /my/family-->
<!--  /my/school-->
  <router-link to="/my/1001/tx">头像</router-link>|
  <router-link to="/my/1002/family">家庭信息</router-link>|
  <router-link to="/my/1003/school">学校信息</router-link>|
  <router-view></router-view>
</div>
</template>
        {
            path:'/my/:id',// :id是用来匹配 路由路径中的变量的
            name:'MyInfo',
            component:MyInfo,
            children:[
                // 子路径要与父类拼接成完整路径
                { path:'tx',component:Touxiang},
                { path:'family',component:Family},
                { path:'school',component:School},
            ]
        },

子组件Touxiang.vue,Family.vue,School.vue中可以使用this.$route.params.id取出路径中的数据1001,1002,1003

16.9 其他

路由重定向,导航守卫等等信息,查看官网自查

重定向| Vue Router (vuejs.org)

导航守卫 | Vue Router (vuejs.org)

路由元信息 | Vue Router (vuejs.org)