Vue3开发 vue-router的使用

2022-08-30 14:15:43

1、vue-router简介

官方介绍:Vue Router 是 Vue.js (opens new window)官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。包含的功能有:

  • 嵌套的路由/视图表
  • 模块化的、基于组件的路由配置
  • 路由参数、查询、通配符
  • 基于 Vue.js 过渡系统的视图过渡效果
  • 细粒度的导航控制
  • 带有自动激活的 CSS class 的链接
  • HTML5 历史模式或 hash 模式,在 IE9 中自动降级
  • 自定义的滚动条行为

用大白话讲,vue-router主要用于构建单页面应用。详细查看官方文档vue-router使用指南

2、路由嵌套

‘/home’路径下有’/home/news’资源,即请求子组件下面子组件。

constHome=()=>import('../components/Home')constHomeNews=()=>import('../components/HomeNews')const route={{
        path:'/home',
        component:Home,
        meta:{
          title:'首页'},
        children:[{
                path:'',
                redirect:'/home/news'},{
                path:'news',
                component:HomeNews},{
                path:'message',
                component:HomeMessage}]}}

3、路由传参

方式一:params
路由格式:path: ‘/user/:userId’
访问路由并传参

<router-link:to="'/user/' + userId"><button>用户</button></router-link>

接收参数 $route.params.userId,$route对象它封装了当前活动的路由。

方式二:query
路由格式(普通路由):path:’/profile’
访问路由并传递参数

<router-link:to="{path:'/profile',query:{id:1,name:'邹越鹏',age:19}}"><button>档案</button></router-link>

接收参数使用$route.query.id。

4、路由的懒加载

先来看看我们普通的导入方式(不推荐使用),用户请求时会自动下载所有相关的组件资源,是EAGER的。

//导入组件import Homefrom'../components/Home'

使用懒加载的方式导入,只有需要该资源的时候就会下载,是Lazy的。

constHome=()=>import('../components/Home')

5、keep-alive与router-view

keep-alive用于保存一个组件的状态,使其不必每次重新渲染,可用于记住我们浏览的某些状态。

创建组件Home,下面案例用于保存Home组件message或news的状态。

<template><h2>我是首页</h2><router-linkto="/home/news"><button>新闻</button></router-link><router-linkto="/home/message"><button>消息</button></router-link><router-view></router-view></template><script>// import {} from 'vue'exportdefault{
        name:"Home",data(){return{
                message:'你好啊',
                path:'/home/news'}},created(){
            console.log('Home created')},//以下两个函数只有在其组件被keep-alive标签保持的时候才会触发activated(){//当前路由活动时调用
            console.log('Home active')this.$router.push(this.path)// console.log('Home active')},// deactivated() {//当前路由失效,退出时调用//     console.log('Home deactivated')// },beforeRouteLeave(to,from){
            console.log('beforeRouteLeave')this.path=this.$route.path;}}</script><stylescoped></style>

路由配置

path:'/home',
component:Home,
 meta:{
   title:'首页',
   keepAlive:true},
 children:[{
         path:'',
         redirect:'/home/news'},{
         path:'news',
         component:HomeNews},{
         path:'message',
         component:HomeMessage}]

keep-alive配合router-view的用法

<router-viewv-slot="{Component}"><component:is="Component"v-if="!this.$route.meta.keepAlive"/><keep-aliveinclude="Home"><component:is="Component"v-if="this.$route.meta.keepAlive"/></keep-alive></router-view>
  • 作者:CV菜鸟#
  • 原文链接:https://blog.csdn.net/m0_51179717/article/details/122173689
    更新时间:2022-08-30 14:15:43