Vue3大事件项目(ing)

文章目录

    • 核心内容
    • 1.大事件项目介绍
    • 2.大事件项目创建
    • 3.Eslint配置代码风格
    • 4.配置代码检查工作流
      • 问题: pnpm lint是全量检查,耗时问题,历史问题
    • 5.目录调整
    • 6.vue-router4 路由代码解析
    • 7.引入 Element Plus 组件库
    • 8.Pinia 构建仓库 和 持久化
    • 9.Pinia 仓库统一管理

核心内容

  1. Vue3 compositionAPI
  2. Pinia / Pinia持久化处理
  3. Element Plus (表单校验,表格处理,组件封装)
  4. pnpm 包管理升级
  5. Eslint + prettier 更规范的配制
  6. husky (Git hooks工具) 代码提交之前,进行校验
  7. 请求模块设计/拦截器,响应拦截器中的处理
  8. 路由设计,VueRouter4
  9. AI 大模型开发一整个项目模块

1.大事件项目介绍

在线演示:https://fe-bigevent-web.itheima.net/login

接口文档:https://apifox.com/apidoc/shared-26c67aee-0233-4d23-aab7-08448fdf95ff/api-93850835

基地址:http://big-event-vue-api-t.itheima.net

2.大事件项目创建

pnpm包管理器 - 创建项目
一些优势:比统类工具快2倍左右、节省磁盘空间 https://www.pnpm.cn/

安装方式:npm install -g pnpm

创建项目:pnpm create vue

Vue3大事件项目(ing)_第1张图片
Vue3大事件项目(ing)_第2张图片
Vue3大事件项目(ing)_第3张图片

3.Eslint配置代码风格

配置文件 .eslintrc.cjs

  1. prettier 配置风格 https://prettier.io
  2. vue组件名称多单词组成(忽略index.vue)
  3. props解构(关闭)
rules: {
	//prettier专注于代码的美观度(格式化工具)
	//前置:
	//1. 禁用格式化插件
	//2. 安装Eslint插件,并配置保存时自动修复

    'prettier/prettier': [
      'warn',
      {
        singleQuote: true, // 单引号
        semi: false, // 无分号
        printWidth: 80, // 每行宽度至多80字符
        trailingComma: 'none', // 不加对象|数组最后逗号
        endOfLine: 'auto' // 换行符号不限制(win mac 不一致)
      }
    ],
    //ESLint关注于规范
    'vue/multi-word-component-names': [
      'warn',
      {
        ignores: ['index'] // vue组件名称多单词组成(忽略index.vue)
      }
    ],
    'vue/no-setup-props-destructure': ['off'], // 关闭 props 解构的校验
    //  添加未定义变量错误提示,[email protected] 关闭,这里加上是为了支持下一个章节演示。
    'no-undef': 'error'
  }

4.配置代码检查工作流

提交2前做代码检查

  1. 初始化 git 仓库,执行git init 即可
  2. 初始化 husky 工具配置,执行 pnpm dlx husky-init && pnpm install 即可
    https://typicode.github.io/husky/
  3. 修改.husky/pre-commit文件
-npm test
+pnpm lint

先下载gitbash
第二步出错时可以换到安全目录执行如$ git config --global --add safe.directory C:/Users/31501/Desktop/a-a-a
还需要在git中设置账户
Vue3大事件项目(ing)_第4张图片
不然无法执行git commit -m

执行之后会提示错误
Vue3大事件项目(ing)_第5张图片

修改错误之后
再次输入
git add .
git commit -m '初始化提交测试'
这是才会成功添加到仓库当中

问题: pnpm lint是全量检查,耗时问题,历史问题

暂存区 eslint校验

  1. 安装 lint-staged 包 pnpm i lint-staged -D
  2. package.json 配置 lint-staged 命令
  3. .husky/pre-commit文件修改

lint-staged 配置

安装
pnpm i lint-staged -D

配置 package.json

{
  // ... 省略 ...
  "lint-staged": {
    "*.{js,ts,vue}": [
      "eslint --fix"
    ]
  }
}

{
  "scripts": {
    // ... 省略 ...
    "lint-staged": "lint-staged"
  }
}

修改 .husky/pre-commit 文件
pnpm lint-staged

报错运行结果

31501@□□ҹ□□□□ MINGW64 ~/Desktop/a-a-a (master)
$ git add .
warning: in the working copy of '.husky/pre-commit', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'package.json', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'pnpm-lock.yaml', LF will be replaced by CRLF the next time Git touches it
warning: in the working copy of 'src/main.js', LF will be replaced by CRLF the next time Git touches it

31501@□□ҹ□□□□ MINGW64 ~/Desktop/a-a-a (master)
$ git commit -m '修改main.js的内容'

> [email protected] lint-staged C:\Users\31501\Desktop\a-a-a
> lint-staged

[STARTED] Preparing lint-staged...
[COMPLETED] Preparing lint-staged...
[STARTED] Running tasks for staged files...
[STARTED] package.json — 4 files
[STARTED] *.{js,ts,vue} — 1 file
[STARTED] eslint --fix
[FAILED] eslint --fix [FAILED]
[FAILED] eslint --fix [FAILED]
[COMPLETED] Running tasks for staged files...
[STARTED] Applying modifications from tasks...
[SKIPPED] Skipped because of errors from tasks.
[STARTED] Reverting to original state because of errors...
[COMPLETED] Reverting to original state because of errors...
[STARTED] Cleaning up temporary files...
[COMPLETED] Cleaning up temporary files...

✖ eslint --fix:

C:\Users\31501\Desktop\a-a-a\src\main.js
  11:13  error  'gaga' is not defined  no-undef

✖ 1 problem (1 error, 0 warnings)

 ELIFECYCLE  Command failed with exit code 1.
husky - pre-commit hook exited with code 1 (error)

把这个改成off
Vue3大事件项目(ing)_第6张图片
再次输入
git add .
git commit -m '往历史代码中模拟一个错误代码'
然后在别的地方在输入一个错误代码
然后再把off改回来,在进行一次校验,他只会对新的错误进行校验,之前的错误不会校验出来

5.目录调整

默认生成的目录结构不满足我们的开发需求,所以这里需要做一些自定义改动

主要是以下工作:

  1. 删除一些初始化的默认文件
  2. 删改剩余代码内容
  3. 新增调整我们需要的目录结构
  4. 拷贝全局样式和图片,安装预处理器支持
  • 安装sass预处理器
  • pnpm add sass -D
  1. 删除文件

  2. 修改内容
    src/router/index.js

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: []
})

export default router

src/App.vue






src/main.js

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(createPinia())
app.use(router)
app.mount('#app')
  1. 新增utils,api
  2. 将项目需要的全局样式 和 图片文件,复制到 assets 文件夹中, 并将全局样式在main.js中引入
import '@/assets/main.scss'

安装 sass 依赖

pnpm add sass -D

6.vue-router4 路由代码解析

基础代码解析

import { createRouter, createWebHistory } from 'vue-router'

// createRouter 创建路由实例,===> new VueRouter()
// 1. history模式: createWebHistory()   http://xxx/user
// 2. hash模式: createWebHashHistory()  http://xxx/#/user

// vite 的配置 import.meta.env.BASE_URL 是路由的基准地址,默认是 ’/‘
// https://vitejs.dev/guide/build.html#public-base-path

// 如果将来你部署的域名路径是:http://xxx/my-path/user
// vite.config.ts  添加配置  base: my-path,路由这就会加上 my-path 前缀了

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: []
})

export default router

import.meta.env.BASE_URL 是Vite 环境变量:https://cn.vitejs.dev/guide/env-and-mode.html
就是地址前面的一格,如果是js,那所有的跳转页面前面都会有一个js
在这里插入图片描述
但是这个不能写死,所以可以在vite.config.js里面配
Vue3大事件项目(ing)_第7张图片

以前的写法

import VueRouter from 'vue-router'
// 初始化 vue-router3.x(Vue2)
const router = new VueRouter({
	mode: 'history',  // 配置路由模式:标识地址栏切换的时候是没有`#`的
	router: [],
})
export default router

vue3中的路由写法
import { createRouter, createWebHistory } from ‘vue-router’
// 初始化 vue-router4.x(Vue3)
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
router: []
})
export default router

1. 创建路由实例由`createRouter`实现
2. 路由模式
	1.history模式使用`createWebHistory`
	2.hash模式使用 `createWebHashHistory()`
	3.参数是基础路径,默认/

PS
router/index.js

import { createRouter, createWebHistory } from 'vue-router'

// createRouter 创建路由实例
// 配置 history ,哦是
// 1.history模式: createWebHistory   地址栏不带 #
// 2.hash模式: createWebHashHistory  地址栏带#
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: []
})

export default router

App.vue


Vue3大事件项目(ing)_第8张图片

7.引入 Element Plus 组件库

官方文档: https://element-plus.org/zh-CN/
找到指南 → 安装(装包) → 快速开始

  1. 安装
$ pnpm add element-plus

自动按需:

  1. 安装插件
pnpm add -D unplugin-vue-components unplugin-auto-import
  1. 然后把下列代码插入到你的 ViteWebpack 的配置文件中
...
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    ...
    AutoImport({
      resolvers: [ElementPlusResolver()]
    }),
    Components({
      resolvers: [ElementPlusResolver()]
    })
  ]
})

  1. 直接使用

而且components下面的组件也可以直接用,当标签用

8.Pinia 构建仓库 和 持久化

在这里插入图片描述
官方文档:https://prazdevs.github.io/pinia-plugin-persistedstate/zh/

  1. 安装插件 pinia-plugin-persistedstate
pnpm add pinia-plugin-persistedstate -D
  1. 使用 main.js
import persist from 'pinia-plugin-persistedstate'
...
app.use(createPinia().use(persist))
  1. 配置 stores/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'

// 用户模块
export const useUserStore = defineStore(
  'big-user',
  () => {
    const token = ref('') // 定义 token
    const setToken = (t) => (token.value = t) // 设置 token

    return { token, setToken }
  },
  {
    persist: true // 持久化
  }
)

9.Pinia 仓库统一管理

在这里插入图片描述
pinia 独立维护

  • 现在:初始化代码在 main.js 中,仓库代码在 stores 中,代码分散职能不单一

  • 优化:由 stores 统一维护,在 stores/index.js 中完成 pinia 初始化,交付 main.js 使用

仓库 统一导出

  • 现在:使用一个仓库 import { useUserStore } from ./stores/user.js 不同仓库路径不一致

  • 优化:由 stores/index.js 统一导出,导入路径统一 ./stores,而且仓库维护在 stores/modules 中

目录如下
Vue3大事件项目(ing)_第9张图片
index.js

import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(persist)

export default pinia

// import { useUserStore } from './modules/user'
// export { useUserStore }

// import { useCountStore } from './modules/counter'
// export { useCountStore }
// 
export * from './modules/user'
export * from './modules/counter'

counter.js

import { defineStore } from 'pinia'
import { ref } from 'vue'

// 数字计数器模块
export const useCountStore = defineStore('big-count', () => {
  const count = ref(100)
  const add = (n) => {
    count.value += n
  }
  return {
    count,
    add
  }
})

App.vue

<script setup>
// 在 Vue3 CompositionAPI中
// 1. 获取路由对象 router useRouter
//    const router = useRouter()
// 2. 获取路由参数 route  useRoute
//    const route = useRoute()
// import { useRoute,useRouter } from 'vue-router'
import { useUserStore, useCountStore } from '@/stores'
// import { useCountStore } from '@/stores/modules/counter.js'
// const router = useRouter() // 获取路由,一个大的路由信息对象
// const route = useRoute() // 路由参数
// const goList = () => {
//   console.log(router, route)
// }

const userStore = useUserStore()
const countStore = useCountStore()
script>

<template>
  <div>
    woshiApp
    <p>{{ userStore.token }}p>
    <el-button @click="userStore.setToken('Bearer uiasfghdukashfk')">
      登录
    el-button>
    <el-button @click="userStore.removeToken()">退出el-button>

    <hr />
    {{ countStore.count }}
    <el-button @click="countStore.add(2)">加法el-button>
  div>
template>

<style scoped>style>

你可能感兴趣的:(vue,案例)