利用 pnpm 创建 vue3 项目


pnpm 包管理器 - 创建项目



Eslint 配置代码风格(Eslint用于规范纠错,prettier用于美观)

在 设置 中配置保存时自动修复



提交前做代码检查
husky是一个 git hooks工具(git的钩子工具,可以在特定实际执行特定的命令)

打开 bash终端

当前项目没有使用 git进行管理,用 git init 进行初始化
然后进行 husky 工具配置,将会在当前目录中新建 一个 .husky 文件夹,其中一个叫 pre-commit,这就是真正在代码提交之前要做的事情。
提交代码之前,可以让其执行 package.json中配置的全局命令 lint ,该命令基于 eslint 校验 vue文件,js文件等一系列文件,


手动调用校验

因为 eslint 是全面检查。耗时,所以解决办法 : 暂存区 eslint 校验

安装 lint-staged 包

package.json中配置 lint-staged命令,如果要执行该命令,还要配置 scripts,也就是lint-staged,一旦触发该命令,就去执行 lint-staged

将内容存放到暂存区并提交

如果代码中有错不能提交,可以先在eslint.cjs中设置关闭,不用管报错先提交

目录调整

将assets,components,stores,views文件夹里的文件删除掉
新增 api 请求文件夹,utils工具文件夹
拷贝全局样式,安装预处理器,进行支持

将图片素材拷贝到 assets 中



在main.js中导入验证是否生效,但是该scss文件在当前项目不支持,,还要安装预处理器

安装 sass预处理器,然后再 pnpm dev 启动

vue-router4路由代码解析:
- 与 vue2 不同:vue2直接导出 VueRouter ,但是vue3是按需导入 createRouter 创建路由(创建实例的方法)
- history有两种模式 createWebHistory 和 createWebHashHistory ,参数是基础路径base,在 vite.config.js中配置
- (在vue3中创建实例用 createApp,创建 路由用 createRouter)
- 如果要在 Vue3 compositionAPI中获取路由对象,要通过路由中导入 useRoute获取路由参数,useRouter获取路由对象



按需引入 Element Plus组件库(因为是 pc 端,所以该组件更合适)
先安装 element-plus
因为按需导入需要两个插件,所以安装两个插件
配置 vite.config.js




配置完成再启动。
可以在项目任意位置使用组件


element-plus组件中还能直接使用其他组件而不用引入
pinia多组件共享数据的需求,通过pinia构建仓库和持久化

在 main.js中引入 createPinia函数,createPinia()会创建一个pinia实例,然后添加到 vue应用中

在 store文件夹中新建 user.js 模块:defineStore新建 仓库,setToken存储内容,removeToken移除内容,token中显示内容

在组件上使用

持久化处理

首先安装插件

将插件应用到 pinia实例中,然后 pinia 实例应用到 vue中

如果希望 某个仓库进行持久化,那么就为其添加第三个参数 persist

关于状态管理 pinia :
- import {createPinia} from 'pinia' 从 pinia库中导入 createPinia 方法(在 main.js中)
- app.use(createPinia()) 在 vue应用中注册 Pinia 实例 。
app.use()
:这是 Vue 3 中的全局插件注册方法。(在 main.js中)- (承上启下)在使用 pinia 时,必须先将pinia实例注册到 vue 应用中,然后才能在仓库 (store)文件中创建和使用 pinia 的 store
- import {defineStore} from 'pinia' 从 pinia库中导入 defineStore函数(在store文件夹下的user.js模块)
- export const useUserStore = defineStore() ,export 是将 useUserStore这个store进行导出,使它能够被外部使用。return 是将 store 中的具体数据和方法(token,setToken,removeToken)暴露出去,让外部能操作这些数据。
- (defineStore中有三个参数,第一个是该仓库唯一标识,第二个是个匿名函数(箭头函数),第三个是进行持久化的参数)
- 要想刷新已有的数据不变,即进行持久化处理,需要安装插件pinia-plugin-persistedstate(git 终端), 在main.js中将其导出,然后应用到 pinia 实例中,而pinia实例用应用到 vue中。然后是 user.js仓库要进行持久化处理,所以为其添加参数 persist:true
Pinia仓库统一管理(两个优化):
- pinia独立维护;原来的 pinia 是堆砌在 main.js中的
- 仓库统一导出;原来的 导出要找到对应的 pinia中的 store,路径很可能找错
pinia独立维护,需要将main.js中与 pinia相关的进行提取到 store文件夹下的 index.js文件中
选中剪切 main.js中与 pinia 有关的代码 ,放入到 stores的index.js中,然后将 pinia 实例导入到 main.js中



仓库统一导出:
stores文件夹下已经有了个 user.js仓库(模块),将来需要处理增加更多的模块处理更多业务,那么会需要一个文件夹modules在stores文件夹下接纳其他仓库文件。在 app.vue中要使用 各个模块下面的数据方法,必须要在app.vue中进行导入,然后获取该各个对象,再然后渲染。
而统一导出就在于 在 app.vue中进行导出各个模块时,必须要写一长串的路径,例如导出user模块,导出路径是 import {useUserStore} from '@/stores/modules/user',每要使用任何一个模块,就必须要导入这么一长串,所以解决办法是将所有模块在 stores文件夹下的 index.js文件中进行导入然后再进行导出,也就是将index.js作为核心出口,那么在app.vue中进行导入的话就直接从 stores文件夹下的 index.js中进行导出了。

