B站尚硅谷VUE项目硅谷甄选(还处于搭建配置中)
2.1项目初始化
使用vite工具初始化项目
使用pnpm安装包,性能优于npm:全局安装pnpm:
npm i -g pnpm
查看版本,确认是否安装成功
pnpm -v
创建项目,桌面新建文件夹,路径输入cmd进入终端,在终端创建vite项目
pnpm create vite
选择文件名、框架与语言
点击project文件夹,进入终端界面,输入 npm i 可采用镜像,速度较快 npm config set registry https://registry.npmmirror.com
输入 pnpm i
(install)安装依赖
输入pnpm run dev
跑在了端口号5173,项目初始化完成
使用vite工具初始化vue’项目
tips:自动生成v3ts模板:
{
"Vue Component Template": {
"prefix": "v3ts",
"body": [
"<template>",
" <div>",
"",
" </div>",
"</template>",
"",
"<script setup lang=\"ts\">",
"",
"</script>",
"",
"<style scoped>",
"",
"</style>"
],
"description": "Basic Vue component structure"
}
}
注意转义字符",,两个双引号容易冲突
2.2项目配置
需要我们手动在浏览器输入地址跑项目,首先配置项目让浏览器自动打开
在package文件中修改"dev": "vite --open",
2.2.1eslint配置
就是这里!!!!eslint把我心态搞崩掉了!!!!
提供插件化的javascript代码检测工具,去检测js代码写的质量高不高
npm i eslint -D
生成配置文件
npx eslint --init
安装完成后,项目会出现eslint.config.js文件,不要慌,可以转化成视频里的.eslintrc.cjs文件
直接修改文件名,将配置文件直接复制进去:
module.exports = {
"env": {
browser: true, // 浏览器环境中的全局变量
es2021: true, // 启用所有 ECMAScript 2021 的特性
node: true, // Node.js 全局变量和 Node.js 作用域
jest: true
},
// 规则继承
"extends": [
"eslint:recommended", // 开启 ESLint 推荐规则
"plugin:vue/vue3-essential", // Vue 3 基础规则
"plugin:@typescript-eslint/recommended" // TypeScript 推荐规则
],
"overrides": [
],
parser: "vue-eslint-parser", // Vue 文件的解析器
parserOptions: {
parser: "@typescript-eslint/parser", // 对 <script> 标签使用 TypeScript 解析器
ecmaVersion: "latest", // 支持最新的 ECMAScript 版本
sourceType: "module", // 模块类型
ecmaFeatures: {
jsx: true // 支持 JSX
}
},
extends: [
"eslint:recommended", // ESLint 推荐规则
"plugin:vue/vue3-essential", // Vue 3 推荐规则
"plugin:@typescript-eslint/recommended", // TypeScript 推荐规则
"plugin:prettier/recommended" // Prettier 推荐规则,确保与 Prettier 的一致性
],
plugins: [
"vue",
"@typescript-eslint"
],
rules: {
"no-var": "error", // 禁止使用 var
"no-multiple-empty-lines": ["warn", { "max": 1 }], // 不允许多个空行
"no-console": process.env.NODE_ENV === 'production' ? 'error' : 'off', // 生产环境禁止 console
"no-debugger": process.env.NODE_ENV === 'production' ? 'error' : 'off', // 生产环境禁止 debugger
"no-unexpected-multiline": "error", // 禁止意外的多行表达式
"no-useless-escape": "off", // 禁止不必要的转义字符
"@typescript-eslint/no-unused-vars": "error", // 禁止定义未使用的变量
"@typescript-eslint/prefer-ts-expect-error": "error", // 鼓励使用 @ts-expect-error 而不是 @ts-ignore
"@typescript-eslint/no-explicit-any": "off", // 允许使用 any 类型
"@typescript-eslint/no-non-null-assertion": "off", // 允许使用非空断言
"@typescript-eslint/no-namespace": "off" ,// 允许使用 TypeScript 命名空间
"vue/multi-word-component-names": "off", // 允许组件名称为单个单词
"vue/script-setup-uses-vars": "error", // 确保 <script setup> 中使用的变量被识别
"vue/no-mutating-props": "off", // 允许修改 props
"vue/attribute-hyphenation": "off" // 对模板中的自定义组件不强制执行属性命名样式
}
}
2.2.2VUE3环境代码校验插件
pnpm install -D eslint-plugin-import eslint-plugin-vue eslint-plugin-node eslint-plugin-prettier eslint-config-prettier eslint-plugin-node @babel/eslint-parser
2.2.3 eslintignore忽略文件
创建这个文件,输入
dist
node_modules
这两个文件不需要校验
2.2.4运行文件
因为不能用var写代码,做个实验,用var写会报错
输入npm run lint校验错误
使用npm run fix 让她自动修改错误,var自动变成const关键字
2.2.5 配置prettier
eslint针对js,检测js语法错误,prettier属于格式化工具,支持js在内的多种语言
eslint保证js代码质量,prettier保证代码美观
1.安装依赖包
npm install -D eslint-plugin-prettier prettier eslint-config-prettier
2.prettierr.json添加规则
{
“singleQuote”: true,
“semi”: false,
“bracketSpacing”: true,
“htmlWhitespaceSensitivity”: “ignore”,
“endOfLine”: “auto”,
“trailingComma”: “all”,
“tabWidth”: 2
}
3.prettierignore忽略文件
# 忽略 dist 目录
/dist/**
# 忽略 HTML 文件
/html/**
# 忽略特定的临时文件
.local
# 忽略所有 node_modules
/node_modules/**
# 忽略所有 SVG 文件
/**/*.svg
# 忽略所有 shell 脚本文件
/**/*.sh
# 忽略 public 目录
/public/**
4.运行脚本,在main文件举个例子,格式有问题的,通过lint查找问题,fix修复问题。来证明 prettier格式化工具很好用
2.2.6 配置stylelint工具
stylelint为css格式化工具,可格式化css代码,检查css语法错误
项目中采用的是scss作为预处理器
npm add sass sass-loader stylelint postcss postcss-scss postcss-html stylelint-config-prettier stylelint-config-recess-order stylelint-config-recommended-scss stylelint-config-standard stylelint-config-standard-vue stylelint-scss stylelint-order stylelint-config-standard-scss --save-dev --legacy-peer-deps
1…stylelintrc.cjs配置文件
module.exports = {
extends: [
'stylelint-config-standard', // 基础 Stylelint 配置
'stylelint-config-standard-scss', // SCSS 特定的 Stylelint 配置
'stylelint-config-recommended-vue/scss', // Vue 中 SCSS 样式格式化推荐配置
'stylelint-config-recess-order', // CSS 属性书写顺序插件
'stylelint-config-prettier' // Stylelint 和 Prettier 兼容配置
],
overrides: [
{
files: ['**/*.{scss,css,vue,html}'],
customSyntax: 'postcss-scss', // SCSS 和 CSS 文件使用 PostCSS-SCSS 解析
rules: {
'value-keyword-case': null, // 在 CSS 中使用-bind时不报错
'no-descending-specificity': null, // 禁止在具有较高优先级的选择器后出现被其覆盖的较低优先级的选择器
'function-url-quotes': 'always', // 要求在 URL 中使用引号
'no-empty-source': null, // 允许空的源文件
'selector-class-pattern': null, // 不强制选择器类名的格式
'property-no-unknown': null, // 允许未知属性
'block-opening-brace-space-before': 'always', // 大括号前必须有一个空格
'value-no-vendor-prefix': null, // 关闭属性值前缀检查,例如 -webkit-box
'selector-pseudo-class-no-unknown': [true, {
ignorePseudoClasses: ['global', 'v-deep', 'deep'] // 忽略特定伪类,以支持 Vue 深度作用选择器
}]
}
},
{
files: ['**/*.{html,vue}'],
customSyntax: 'postcss-html' // HTML 和 Vue 文件使用 PostCSS-HTML 解析
}
],
ignoreFiles: [
'**/dist/**', // 忽略 dist 目录
'**/node_modules/**' // 忽略 node_modules 目录
],
rules: {
'no-empty-source': null, // 全局配置中也允许空的源文件
'property-no-vendor-prefix': null, // 全局配置中关闭属性前缀检查
'selector-pseudo-class-no-unknown': [true, {
ignorePseudoClasses: ['global', 'v-deep', 'deep'] // 同样,全局配置中忽略 Vue 特定伪类
}]
}
};
2.stylelintignore忽略文件
dist/**
# 忽略 html 目录
html/**
# 忽略 public 目录
public/**
# 忽略 node_modules 目录
node_modules/**
3.运行脚本
2.2.7配置husky
已集成好代码校验工具,需要手动执行命令才能格式化代码。
现在可以哟个husky在代码提交前触发git hook(git 在客户端的钩子),然后执行npm run format自动格式化我们的代码
npm install -D husky --legacy-peer-deps
TIPS:有依赖冲突时在后面加上–legacy-peer-deps
1.把项目初始化为git仓库
git init
2.运行husky初始化命令
npx husky-init
3.把本地仓库代码提交到远程仓库中:
添加一个新的远程仓库,可以推送push和pull拉取代码,
$ git remote add origin https://gitee.com/shinnying/vue3_admin_template-bj1.git
只能右击选择复制paste
git add .
以上代码是将当前目录下的所有更改(删除文件、修改文件等)添加到git暂存区,之后才能被提交到仓库历史中
$ git commit -m '提交没有格式化的代码'
提交的时候会让你配置用户信息,git需要知道这个提交是谁做的,输入你的用户名和邮箱即可
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
推送代码到远程仓库
$ git push -u origin "master"
之后会弹出对话框,输入我git的账号和密码
推送代码成功
2.2.8配置commitlint
对于commit信息,也要统一规范
1.安装依赖包
npm add @commitlint/config-conventional @commitlint/cli -D --legacy-peer-deps
2.添加配置文件commitlint.config.cjs
module.exports = {
extends: ['@commitlint/config-conventional'],
// 校验规则
rules: {
'type-enum': [
2,
'always',
[
'feat',//新特性,新功能
'fix',//修改bug
'docs',//文档修改
'style',//代码格式修改,注意不是css
'refactor',//代码重构
'perf',//优化相关,比如提升性能、体验
'test',//测试用例修改
'chore',//其他修改,比如改变构建流程,或者增加依赖库、工具等
'revert',//回滚到上个版本
'build'//编译相关的修改,例如发布版本、对项目构建或者依赖的改动
]
],
'type-case': [0],
'type-empty': [0],
'scope-empty': [0],
'scope-case': [0],
'subject-full-stop': [0, 'never'],
'subject-case': [0],
'header-max-length': [0, 'always', 72]
}
};
3.在package.json配置script命令
"commitlint": "commitlint --config commitlint.config.cjs -e -v"
4.配置husky
npx husky add .husky/commit-msg
pnpm commitlint
5.git上传
git commit -m 'feat: addh1'
2.2.9强制使用pnpm包管理器工具
在团队开发项目的时候需要统一的包管理器,因为不同包管理器工具下载同一个依赖,可能版本不一样,导致项目出现bug问题
1.在根目录下创建scripts/preinstall.js文件
if (!/pnpm/.test(process.env.npm_execpath)) {
console.warn(
'\u001b[33mThis repository must use pnpm as the package manager for scripts to work properly.\u001b[39m\n'
);
process.exit(1);
}
2.配置命令
"preinstall": "node ./scripts/preinstall.js"
TIPS:npm也可以下载,评论说npm后面的版本,preinstall已经不在脚本前面运行了
三、项目集成
3.1 集成element-plus
pnpm install element-plus
1.main.ts文件
import { createApp } from 'vue'
import App from './App.vue'
// 引入element-plus插件与样式
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
// element-plus国际化配置
import zhCn from 'element-plus/es/locale/lang/zh-cn'
// 获取应用实例对象
const app = createApp(App)
// 安装element-plus插件
app.use(ElementPlus,{
locale:zhCn//element-plus国际化配置
});
// 将应用挂载到挂载点上
app.mount('#app')
2.举例,关于element-plus
在这里我卡了两个小时!!!一直在找为什么我的vue不能自动补全代码!!!
vue3自动补全代码是用 Volar 插件,但是volar插件最近被更名为vue-officier!!!!
尝试了vue snipps和vue helper都不好用,令人头大!!!!
<el-button type="primary" size="default" :icon="Plus">主要按钮</el-button>
<el-button type="success" size="small" :icon="Edit"> 编辑按钮</el-button>
<el-button type="danger" size="default" :icon="Delete"> 编辑按钮</el-button>
<el-pagination :page-size="100" layout="total, prev, pager, next" :total="1000" />
3.配置element-plus国际化,在官网找到代码复制过去就ok
import zhCn from 'element-plus/es/locale/lang/zh-cn'
app.use(ElementPlus,{
locale:zhCn//element-plus国际化配置
});
3.2src别名的配置
在开发项目的时候文件与文件关系可能很复杂,我们需要给src文件配置别名,用@代替src
- vite.config文件配置
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import path from 'path';
export default defineConfig({
plugins: [
vue(),
Components({
resolvers: [ElementPlusResolver()],
}),
],
resolve: {
alias: {
"@": path.resolve("./src")
}
}
});
- ts编译配置
"paths": { // 路径映射,相对于 baseUrl "@/*": [ "src/*" ] // 将 "@" 符号映射到 "src" 目录 }
3.新建test文件进行测试
可以通过别名引用
3.3环境变量的配置
在开发项目过程中会经历开发环境、测试环境和生产环境三个阶段,不同的阶段请求的状态(如接口地址)不同,三个阶段对应三台服务器,三个服务器的域名和端口号不一样,我们在开发项目时要配置代理化域,手动切换接口地址过程繁琐且易出错,通过环境变量配置切换接口
开发环境(development)
开发使用的环境,每个开发人员在自己的dev分支干活,开发到一定程度,同事会合并代码,进行联调
测试环境(testing)
测试同事自己部署,用于测试
生产环境(production)
正式提供对外服务,一般会关掉错误报告,打开错误日志
一般情况下一个服务对应一台服务器,有的公司测试与开发使用一台服务器
1.在package.json配置运行命令
# 变量以VITE_为前缀才能暴露给外面读取
NODE_ENV = 'development'
VITE_APP_TITLE = '硅谷甄选运营平台'
VITE_APP_BASE_API = '/dev-api'
VITE_SERVE = 'http://xxxx.com'
2.通过import.meta.env获取环境变量
3.4SVG图标配置
在开发项目时会用到svg矢量图标,比较出名的是阿里图标库,使用svg之后,页面加载的不是图标资源,提高页面性能,svg文件比img小很多,不占用资源
1.下载插件 pnpm install vite-plugin-svg-icons -D
2.配置vite.config.ts
// 引入svg需要用到的插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
symbolId: 'icon-[dir]-[name]'
})
3.入口文件导入配置项
// svg插件需要的配置代码
import 'virtual:svg-icons-register'
4.svg测试
<template>
<div>
<h1>SVG测试</h1>
<!-- 测试svg图标使用 -->
<svg style="width: 30px;height: 30px;">
<!-- href执行使用哪个图标 -->
<use href="#icon-phone" fill="red"></use>
</svg>
</div>
</template>
<script setup lang="ts">
// import SvgIcon from '@/components/Svgicon/index.vue';
</script>
<style scoped></style>
TIPS:xlink-href被废弃了,在新的浏览器版本直接使用href就可以了,不然显示不出我的图标
5. 封装组件
把上述svg封装成组件
<template>
<svg style={width,height}>
<!-- href执行使用哪个图标 -->
<use :href="prefix + name" :fill="color"></use>
</svg>
</template>
<script setup lang="ts">
// 接受父组件传递过来的参数
defineProps({
// xlink:href的前缀
prefix: {
type: String,
default: '#icon-'
},
// 提供使用图标的名字
name: String,
// 接收父组件传递的颜色
color: {
type: String,
default: ''
},
// 接受父组件传递过来的宽度
width: {
type: String,
default: '16px'
},
// 接受父组件传递过来高度
height: {
type: String,
default: '16px'
},
})
</script>
<style scoped></style>
<!-- 测试svg图标使用 -->
<svg-icon name="home" color="pink" width="100px" height="100px"></svg-icon>
6.测试结果
3.5定义svg-icon组件为全局组件
只需要注册一次,不需要再其他地方引入直接使用
1.在入口文件main.ts直接引入注册
import SvgIcon from '@/components/Svgicon/index.vue';
app.component('SvgIcon',SvgIcon);
app.component函数用于注册
2.组件较多的话可以利用自定义插件,将组件自动定义
2.1在components创建index.ts文件
// 引入项目中全局组件
import SvgIcon from "./SvgIcon/index.vue";
import Pagination from "./Pagination/index.vue";
// 全局对象
const allGlobalComponent = { SvgIcon, Pagination }
// 对外暴露插件对象
export default {
// 务必叫install方法
install(app) {
// 注册项目全部的全局组件
// foreach函数,列出数组的每个元素
// objects.keys静态方法返回一个数组
Object.keys(allGlobalComponent).forEach(key => {
// 注册为全局组件,key是名称,allGlobalComponent[key]是配置对象
app.component(key, allGlobalComponent[key]);
})
}
}
install方法会把app应用实例注册进来,打印app会有component方法
2.2在main.ts文件
// 引入自定义插件对象:注册整个项目的全局组件
import globalComponent from '@/components';
// 安装自定义插件
app.use(globalComponent);
2.3在app.vue测试一下
<!-- 测试svg图标使用 -->
<Pagination></Pagination>
<svg-icon name="phone"></svg-icon>
3.6 集成sass预处理器
组件内部可以使用scss样式,在配置stylelint工具,项目已经安装过了sass-loader,在组件内可以使用sass,需要加上lang= ‘scss’
1.配置全局变量
在vite.config.ts配置全局变量
css: {
// 配置预处理器选项
preprocessorOptions: {
scss: {
// 启用 JavaScript
javascriptEnabled: true,
// 全局数据(变量、混入等)
additionalData: '@import "./src/styles/variables.scss";'
}
}
}
2.在变量文件variables.scss文件夹添加全局变量
scss变量符号使用$表示,less变量符号用@表示
// 项目提供scss全局变量
$color:red;
3.测试
<style scoped lang="scss">
div {
h1 {
color: $color;
}
}
</style>
3.7mock数据
用于制造假的接口项目,后台管理项目一般有登录,获取用户信息,退出登录接口
根据官网https://www.npmjs.com/package/vite-plugin-mock/v/2.9.6配置mock插件,选用 2.9.6版本(评论区有人说高版本容易报错)
1.按照步骤安装:
npm i mockjs -S
npm i vite-plugin-mock -D
2.配置vite.config.js文件
把原来的函数换成箭头函数:
// command用于获取当前开发环境。mock接口只用于开发
export default defineConfig(({ command }) => {
return {
plugins: [
vue(),
Components({
resolvers: [ElementPlusResolver()],
}),
createSvgIconsPlugin({
iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
symbolId: 'icon-[dir]-[name]'
}),
viteMockServe({
localEnabled: command === 'serve',//开发阶段可以使用mock接口
}),
],
resolve: {
alias: {
"@": path.resolve("./src")
}
},
// scss全局变量配置
css: {
// 配置预处理器选项
preprocessorOptions: {
scss: {
// 启用 JavaScript
javascriptEnabled: true,
// 全局数据(变量、混入等)
additionalData: '@import "./src/styles/variables.scss";'
}
}
}
}
3.在根目录下创建mock文件夹下创建ts文件:存放需要的mock数据与接口
//createUserList:此函数执行会返回一个数组,数组里面包含两个用户信息
function createUserList() {
return [
{
userId: 1,
avatar:
'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
username: 'admin',
password: '111111',
desc: '平台管理员',
roles: ['平台管理员'],
buttons: ['cuser.detail'],
routes: ['home'],
token: 'Admin Token',
},
{
userId: 2,
avatar:
'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
username: 'system',
password: '111111',
desc: '系统管理员',
roles: ['系统管理员'],
buttons: ['cuser.detail', 'cuser.user'],
routes: ['home'],
token: 'System Token',
},
]
}
// 对外暴露一个数组,数组里面有两个接口
// 登录假的接口
// 获取用户信息假的接口
export default [
// 用户登录接口
{
url: '/api/user/login',//请求地址
method: 'post',//请求方式
response: ({ body }) => {
//获取请求体携带过来的用户名与密码
const { username, password } = body;
//调用获取用户信息函数,用于判断是否有此用户
const checkUser = createUserList().find(
(item) => item.username === username && item.password === password,
)
//没有用户返回失败信息
if (!checkUser) {
return { code: 201, data: { message: '账号或者密码不正确' } }
}
//如果有返回成功信息
const { token } = checkUser
return { code: 200, data: { token } }
},
},
// 获取用户信息
{
url: '/api/user/info',
method: 'get',
response: (request) => {
//获取请求头携带token
const token = request.headers.token;
//查看用户信息是否包含有次token用户
const checkUser = createUserList().find((item) => item.token === token)
//没有返回失败的信息
if (!checkUser) {
return { code: 201, data: { message: '获取用户信息失败' } }
}
//如果有返回成功信息
return { code: 200, data: { checkUser } }
},
},
]
4.测试一下
在入口文件main.ts测试
// 测试代码:测试假的接口能否使用
import axios from 'axios';
// 登录接口
axios({
url: '/api/user/login',
method: 'post',
data: {
username: 'admin',
password: '111111'
}
})
点击网络,选择login,点击负载可以看到接口显示用户名和密码
3.8 API统一接口管理
1.新建src/api/user文件夹管理用户接口
在该文件夹简历index.ts(管理用户接口)type.ts(管理接口类型)
2.index.ts
// 统一管理项目用户相关的接口
import request from "@/utils/request";
import type { loginForm, loginresponseData, userResponseData } from "./type";
// 统一管理接口
enum API {
LOGIN_URL = '/user/login',
USERINFO_URL = '/user/info'
}
// 对外暴露请求函数
// 登录接口方法
export const reqLogin = (data: loginForm) => request.post<any, loginresponseData>(API.LOGIN_URL, data);
// 获取用户信息
// 通过请求头携带参数,这里不需要带参数
export const reqUserInfo = () => request.get<any, userResponseData>(API.USERINFO_URL)
enum是枚举类型,提供常量值
// <any, loginresponseData>泛型类型参数的使用,
// any表示请求可以接收任何数据类型,响应只接收这个loginresponseData类型的响应
3.type.ts
// 登录接口需要携带参数ts类型
export interface loginForm {
uername: string,
password: string
}
interface dataType {
token: string
}
// 登录接口返回数据类型
export interface loginresponseData {
code: number,
data: dataType
}
// 定义服务器返回用户信息相关的数据类型
interface userInfo {
uerId: number,
avatar: string,
username: string,
password: string,
desc: string,
roles: string[],
buttons: string[],
routes: string[],
token: string
}
interface user {
checkUser: {
}
}
export interface userResponseData {
code: number,
data: user
}
4.测试登录
<template>
<div>
<h1>APP根组件</h1>
</div>
</template>
<script setup lang="ts">
// 挂载vue
import { onMounted } from 'vue';
import { reqLogin } from './api/user';
onMounted(() => {
reqLogin({ username: 'admin', password: '123456' })
})
</script>
<style scoped></style>