Vue3+vite搭建基础架构(6)--- 使用vue-router

2024-02-19 06:52

本文主要是介绍Vue3+vite搭建基础架构(6)--- 使用vue-router,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Vue3+vite搭建基础架构(6)--- 使用vue-router

  • 说明
  • 官方文档
  • 安装vue-router
  • 使用vue-router
  • 测试vue-router

说明

这里记录下自己在Vue3+vite的项目使用vue-router的过程,不使用ts语法,方便以后直接使用。这里承接自己的博客Vue3+vite搭建基础架构(5)— 使用vue-i18n这篇博客,在该博客项目的基础上增加使用vue-router。

官方文档

Vue3使用vue-router官方文档:https://router.vuejs.org/zh/installation.html

安装vue-router

根据官网给的安装命令如下:

npm install vue-router@4

在webstorm里面的Terminal输入npm install vue-router@4命令安装该依赖。执行完如下:
在这里插入图片描述

package.json会增加vue-router版本号
在这里插入图片描述

使用vue-router

在src目录下新建router文件夹,在该文件夹里面创建一个index.js文件。
在这里插入图片描述

router文件夹下的index.js代码:

//引入router路由做页面请求
import { createRouter,createWebHashHistory } from 'vue-router'
/* Layout通用组件 */
import Layout from '../views/layout/layout'//前端页面路由地址
const routes = [{path: '/404', component: () => import('@/views/404')},//必须要把组件放在Layout的children里面,才能在侧边栏的右侧显示页面内容,否则不加载通用架构直接在当前空白页面渲染内容,如:404页面{path: '',component: Layout,redirect: '/home',children: [{path: 'home',name: 'home',component: () => import('@/views/home/index'),meta: {title: '首页', icon: 'home'}},{path: 'hello',name: 'hello',component: () => import('@/components/HelloWorld'),meta: {title: '测试页', icon: 'hello'}}]}
]// 3. 创建路由实例并传递 `routes` 配置
const router = createRouter({// 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。history: createWebHashHistory(),routes, // `routes: routes` 的缩写
})//路由前置守卫
router.beforeEach((to, from, next) => {//路由发生变化修改页面titleif (to.meta.title) {document.title = to.meta.title}next()
})//导出路由
export default router

在main.js里面引入router配置:
在这里插入图片描述
代码如下:

import { createApp } from 'vue'
//引入element-plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
//将element-plus里面默认语言英文改为中文,需要引入它
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
//引入dayjs日期插件
import dayjs from 'dayjs'
//引入国际化配置
import lang from './locale'
//引入router路由
import router from './router'
import './style.css'
import App from './App.vue'const app = createApp(App)
//使用element-plus,并设置语言为中文
app.use(ElementPlus, {locale: zhCn,
})
//通过provide全局注入工具函数
app.provide('$dayjs', dayjs)
//国际化配置使用
app.use(lang)
//使用router路由
app.use(router)
app.mount('#app')

路由里面配置了几个页面地址,这里贴上对应页面代码,404图片随便网上找一个就行。
在这里插入图片描述

在src目录下新建views文件夹,在views文件夹下新建404.vue页面。
404页面代码如下:

<template><div><div class="app-container"><el-col :span="12"><img :src="img_404" alt="404" class="img-style"></el-col><el-col :span="12"><div style="margin-left: 100px;margin-top: 60px"><h1 class="color-main">OOPS!</h1><h2 style="color: #606266">很抱歉,页面它不小心迷路了!</h2><div style="color:#909399;font-size: 14px">请检查您输入的网址是否正确,请点击以下按钮返回主页或者发送错误报告</div><el-button style="margin-top: 20px" type="primary" round @click="handleGoMain">返回首页</el-button></div></el-col></div></div>
</template><script setup>import img_404 from '@/assets/images/gif_404.gif'import { useRouter } from "vue-router"//使用router跳转路由const router=useRouter()const handleGoMain = () => {//跳转到首页router.push({ path: '/home' })}</script><style scoped>.app-container {width: 80%;margin: 120px auto;}.img-style {width: auto;height: auto;max-width: 100%;max-height: 100%;}
</style>

home文件夹下的index.js代码,将App.vue页面代码移到home文件夹下的index.js里面:

<template><p>当前语言的title值:{{$t('title')}}</p><p>当前语言的title值:{{t('title')}}</p><el-button type="primary">Primary</el-button><el-button type="success">Success</el-button><!--日期选择器--><el-date-pickerv-model="dateValue"type="date"placeholder="请选择一天"/>
</template><script setup name="home">import {ref, inject, onMounted ,getCurrentInstance} from 'vue'import {getCurrentDate,getDateDiff,getXBeforeDate,getIntermediateDate} from '@/utils/dateUtil'import {login,test} from '@/api/login'import { useI18n } from 'vue-i18n'console.info("useI18n()=",useI18n())//使用i18nconst {t,locale} = useI18n()//日期变量,使用ref进行双向绑定const dateValue = ref('')//获取日期变量值,需要加.value来获取值console.info("dateValue=",dateValue.value)//onMounted页面初始化完成后执行onMounted(()=>{//获取在main.js里面使用provide全局注册的函数/*const dayjs=inject('$dayjs')//使用dayjs将当前时间转换为指定样式console.log("dayjs=",dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'))//使用dateUtil工具类获取当前时间console.log("当前日期=",getCurrentDate())//计算2个日期之间相差多少天,只要开始日期和结束日期格式保持一致就行,日期格式为YYYY-MM-DD或者YYYY-MM-DD HH:mm:ss都能计算console.log("相差天数为=",getDateDiff('2024-02-01','2024-03-01','day'))//获取之前日期console.log("获取当前日期的前6天日期=",getXBeforeDate(getCurrentDate(),6,'day'))//获取开始日期与结束日期之间的所有日期console.log("开始日期到结束日期=",getIntermediateDate('2024-02-01','2024-02-15',1,'day'))//接口请求发送示例const data={username:"test111",password:"123456"}test(data).then(response => {console.info("请求成功")}).catch(error => {console.log(error)})*///获取当前语言类型console.log("当前语言:",locale.value)//将默认语言中文改为英文locale.value='en'console.log("当前语言:",locale.value)})
</script><style scoped></style>

App.vue下修改后的代码如下:

<template><div><!--路由入口 在App.vue中使用<router-view>组件来渲染要显示的组件--><router-view/></div>
</template><script setup name="App"></script><style scoped></style>

layout文件夹下的layout.vue代码:

<template><div><el-container><!--头部--><el-header><Navbar></Navbar></el-header><el-container><!--侧边栏--><el-aside width="200px"><SliderBar></SliderBar></el-aside><!--主体内容--><el-main><AppMain></AppMain></el-main></el-container></el-container></div>
</template><script>import { Navbar, SliderBar, AppMain } from './components/index.js'export default {name: "layout",components: {Navbar,SliderBar,AppMain}}
</script><style scoped></style>

layout文件夹下components文件夹下的navbar.vue代码:

<!--通用布局头部内容-->
<template><div>我是头部</div>
</template><script setup name="navbar"></script><style scoped></style>

layout文件夹下components文件夹下的appMain.vue代码:

<!--通用布局页面主体内容-->
<template><div><!--页面内容加载在这里--><router-view></router-view></div>
</template><script setup name="AppMain"></script><style scoped></style>

layout文件夹下components文件夹下sliderBar下的sliderBar.vue代码:

<!--通用布局侧边栏内容-->
<template><div>我是侧边栏</div>
</template><script setup name="SliderBar"></script><style scoped></style>

layout文件夹下components文件夹下sliderBar下的menuTree.vue代码:

<!--菜单树列表-->
<template></template><script setup name="MenuTree"></script><style scoped></style>

layout文件夹下components文件夹下的index.js代码:

export { default as Navbar} from './navbar.vue'
export { default as SliderBar } from './sliderBar/sliderBar.vue'
export { default as AppMain } from './appMain'

测试vue-router

默认进入首页测试,浏览器结果如下:
在这里插入图片描述
404页面测试,浏览器结果如下:
在这里插入图片描述
hello测试页浏览器结果如下:
在这里插入图片描述
这里通用布局layout组件是在页面中间,解决方式是在main.js删除默认的全局样式。删除这句代码,后面全局样式引入自己写的。如下:
在这里插入图片描述
结果如下,不在显示在页面中间,显示正常:
在这里插入图片描述

到这里router路由测试就结束了,页面可以正常跳转,说明router引入没有问题,layout通用布局页面先写个空的,等后面写菜单栏的时候会用上。

这篇关于Vue3+vite搭建基础架构(6)--- 使用vue-router的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/723835

相关文章

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

gitlab安装及邮箱配置和常用使用方式

《gitlab安装及邮箱配置和常用使用方式》:本文主要介绍gitlab安装及邮箱配置和常用使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1.安装GitLab2.配置GitLab邮件服务3.GitLab的账号注册邮箱验证及其分组4.gitlab分支和标签的

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

nginx启动命令和默认配置文件的使用

《nginx启动命令和默认配置文件的使用》:本文主要介绍nginx启动命令和默认配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录常见命令nginx.conf配置文件location匹配规则图片服务器总结常见命令# 默认配置文件启动./nginx

在Windows上使用qemu安装ubuntu24.04服务器的详细指南

《在Windows上使用qemu安装ubuntu24.04服务器的详细指南》本文介绍了在Windows上使用QEMU安装Ubuntu24.04的全流程:安装QEMU、准备ISO镜像、创建虚拟磁盘、配置... 目录1. 安装QEMU环境2. 准备Ubuntu 24.04镜像3. 启动QEMU安装Ubuntu4

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本