第五章、Vue3高级
目录- 二十一、项目搭建规范
- 1、创建项目
- 2、代码规范
- a、.editorconfig(编辑器编辑风格)
- b、prettier(代码格式化风格)
- c、eslint(代码风格检测工具)
- d、git Husky(提交前代码格式化风格)
- e、commitizen(提交信息格式化风格)
- f、commitlint(提交信息风格检测工具)
- 3、项目结构
- a、vue.config.js
- b、vue-router
- c、vuex
- d、element-plus
- e、axios
- f、环境变量
- g、tsconfig.json
- h、shims-vue.d.ts
- 二十二、项目实战细节
二十一、项目搭建规范
1、创建项目
vue create vue3-ts
? Please pick a preset:
- Manually select features
? Check the features needed for your project:
- Choose Vue version, Babel, TS, Router, Vuex, CSS Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with
- 3.x
? Use class-style component syntax?
- No
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)?
- Yes
? Use history mode for router? (Requires proper server setup for index fallback in production)
- No
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default):
- Sass/SCSS (with dart-sass)
? Pick a linter / formatter config:
- Prettier
? Pick additional lint features:
- Lint on save
? Where do you prefer placing config for Babel, ESLint, etc.?
- In dedicated config files
? Save this as a preset for future projects?
- No
? Pick the package manager to use when installing dependencies:
- NPM
2、代码规范
a、.editorconfig(编辑器编辑风格)
# http://editorconfig.org
root = true
[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行
[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off
trim_trailing_whitespace = false
b、prettier(代码格式化风格)
npm i -D prettier
{
"useTabs": false,
"tabWidth": 2,
"printWidth": 80,
"singleQuote": true,
"trailingComma": "none",
"semi": false
}
* useTabs:使用tab缩进还是空格缩进,选择false
* tabWidth:tab是空格的情况下,是几个空格,选择2个
* printWidth:当行字符的长度,推荐80,也有人喜欢100或者120
* singleQuote:使用单引号还是双引号,选择true,使用单引号
* trailingComma:在多行输入的尾逗号是否添加,设置为 `none`
* semi:语句末尾是否要加分号,默认值true,选择false表示不加
/dist/*
.local
.output.js
/node_modules/**
**/*.svg
**/*.sh
/public/*
{
"scripts": {
"prettier": "prettier --write ."
}
}
c、eslint(代码风格检测工具)
npm i -D eslint-plugin-prettier eslint-config-prettier
module.exports = {
root: true,
env: {
node: true
},
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/typescript/recommended',
'@vue/prettier',
'@vue/prettier/@typescript-eslint',
// 解决eslint和prettier的冲突
'plugin:prettier/recommended'
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off'
}
}
d、git Husky(提交前代码格式化风格)
################
# 1、用于拦截git命令
# 2、项目三处变化:
# - package.json多一个依赖({"devDependencies": {"husky": ""}})
# - 项目下多一个.husky目录
# - package.json多一个脚本({"scripts": {"prepare": "husky install"}})
################
npx husky-init && npm install
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npm run lint
e、commitizen(提交信息格式化风格)
npm i -D commitizen
################
# 1、项目两处变化:
# - package.json多一个依赖({"devDependencies": {"cz-conventional-changelog": ""}})
# - package.json多一个配置
# ({"config": {"commitizen": {"path": "./node_modules/cz-conventional-changelog"}}})
################
npx commitizen init cz-conventional-changelog --save-dev --save-exact
- package.json(代码的git提交操作使用此脚本)
{
"scripts": {
"commit": "cz"
}
}
? Select the type of change that you're committing:
- 提交的类型
? What is the scope of this change (e.g. component or file name): (press enter to skip)
- 提交的范围
? Write a short, imperative tense description of the change (max 87 chars):
- 提交的简短描述信息
? Provide a longer description of the change: (press enter to skip)
- 提交的详细描述信息
? Are there any breaking changes?
- No
? Does this change affect any open issues?
- No
提交的类型 |
作用 |
feat
新增特性 (feature)
fix
修复 Bug(bug fix)
docs
修改文档 (documentation)
style
代码格式修改(white-space, formatting, missing semi colons, etc)
refactor
代码重构(refactor)
perf
改善性能(A code change that improves performance)
test
测试(when adding missing tests)
build
变更项目构建或外部依赖(例如 scopes: webpack、gulp、npm 等)
ci
更改持续集成软件的配置文件和 package 中的 scripts 命令,例如 scopes: Travis, Circle 等
chore
变更构建流程或辅助工具(比如更改测试环境)
revert
代码回退
f、commitlint(提交信息风格检测工具)
npm i -D @commitlint/config-conventional @commitlint/cli
module.exports = {
extends: ['@commitlint/config-conventional']
}
################
# 1、项目一处变化:
# - .husky下多一个commit-msg文件
################
npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"
3、项目结构
a、vue.config.js
const path = require('path')
module.exports = {
// 1、方式一: 通过Vue CLI提供的选项来配置(推荐)
outputDir: 'dist',
publicPath: '/',
// 2、方式二: 通过configureWebpack(与webpack配置选项一致)
// 2.1、对象:合并webpack配置
configureWebpack: {
resolve: {
alias: {
components: '@/components'
}
}
},
// 2.2、函数:修改webpack配置
/*
configureWebpack: (config) => {
config.resolve.alias = {
'@': path.resolve(__dirname, 'src'),
components: '@/components'
}
},*/
// 3、方式三:通过chainWebpack(与webpack配置选项一致)
// 3.1、函数:修改webpack配置
/*
chainWebpack: (config) => {
config.resolve.alias
.set('@', path.resolve(__dirname, 'src'))
.set('components', '@/components')
}*/
}
b、vue-router
npm i -S vue-router@next
import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
redirect: '/home'
},
{
path: '/home',
component: () => import('../views/Home.vue')
},
{
path: '/about',
component: () => import('../views/About.vue')
}
]
const router = createRouter({
history: createWebHashHistory(),
routes
})
export default router
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
<template>
<div>
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
</div>
<router-view />
</template>
c、vuex
npm i -S vuex@next
import { createStore, useStore as useVuexStore } from 'vuex'
import user, { IUserState } from './modules/user'
export interface IRootState {
user: IUserState
}
export default createStore<IRootState>({
modules: {
user
}
})
export function useStore() {
return useVuexStore<IRootState>()
}
- src/store/modules/user.ts
import { IRootState } from '@/store'
export interface IUserState {
token: string
userInfo: {
id: string
nickname: string
}
}
const user: Module<IUserState, IRootState> = {
namespaced: true,
state() {
return {
token: '',
userInfo: {
id: '',
nickname: ''
}
}
},
mutations: {},
actions: {}
}
export default user
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'
const app = createApp(App)
app.use(store)
app.mount('#app')
<template>
<div></div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { useStore } from '@/store'
export default defineComponent({
setup() {
const store = useStore()
console.log(store.state.user.token)
return {}
}
})
</script>
<style lang="scss" scoped></style>
d、element-plus
npm i -S element-plus
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
<template>
<el-button type="primary">黄婷婷</el-button>
</template>
e、axios
npm i -S axios
* Promise<any>指定了泛型,则resolve(res)和.then(res=>{})的res就是any类型
* axios配置默认值优先级:请求的config参数 > 实例的defaults属性
* axios实例多个拦截器会合并,执行顺序是从后往前
import axios from 'axios'
import type { AxiosRequestConfig } from 'axios'
import Cookies from 'js-cookie'
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000
})
service.interceptors.request.use(
(config) => {
// 1、请求头添加令牌
const token = Cookies.get('token')
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(error) => {
return Promise.reject(error)
}
)
service.interceptors.response.use(
(response) => {
// 2、处理后端接口统一响应结果的状态码
switch (response.data.code) {
case 999:
console.log('错误')
break
default:
}
return response
},
(error) => {
// 3、处理http的状态码
switch (error.response.status) {
case 401:
console.log('未认证或令牌过期')
break
case 403:
console.log('无权限访问拒绝')
break
default:
}
return Promise.reject(error)
}
)
interface IResponseBody<T = any> {
code: number
data: T
message: string
}
export default function <T = any>(
config: AxiosRequestConfig
): Promise<IResponseBody<T>> {
return service(config).then((res) => {
return res.data
})
}
import request from '@/utils/request'
export function login(data: any) {
return request({
url: '/user/login',
method: 'post',
data
})
}
<template>
<div></div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { login } from '@/api/user'
export default defineComponent({
setup() {
login({}).then((res) => {
console.log(res)
})
return {}
}
})
</script>
<style lang="scss"></style>
f、环境变量
* 模式:
- 脚本命令:vue-cli-service serve(默认--mode development)
引用文件:.env.development
NODE_ENV:process.env.NODE_ENV = "development"
- 脚本命令:vue-cli-service build(默认--mode production)
引用文件:.env.production
NODE_ENV:process.env.NODE_ENV = "production"
- 脚本命令:vue-cli-service build --mode staging(手动指定)
引用文件:.env.staging
NODE_ENV:process.env.NODE_ENV = "staging"
* NODE_ENV变量无需手动赋值
* 其他变量应以VUE_APP_开头才会自动注入到代码中
* .env优先级小于.env.development或.env.production等
g、tsconfig.json
{
"compilerOptions": {
// 目标代码:babel编译(esnext),tsc编译(es5)
"target": "esnext",
// 目标代码模块化方案:es模块化方案(esnext),模块化方案混合使用(umd)
"module": "esnext",
// ts严格模式
"strict": true,
// jsx处理:不转化处理(preserve)
"jsx": "preserve",
// 导入功能辅助
"importHelpers": true,
// 解析模块方式:后缀名顺序查找文件(node)
"moduleResolution": "node",
// 跳过第三方库的类型检测
"skipLibCheck": true,
// 源代码模块化方案:模块化方案混合使用
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
// 是否生成映射文件
"sourceMap": true,
// 文件解析路径
"baseUrl": ".",
// 解析类型
"types": [
"webpack-env"
],
// 路径别名(与webpack配置对应)
"paths": {
"@/*": [
"src/*"
]
},
// 基础类型库
"lib": [
"esnext",
"dom",
"dom.iterable",
"scripthost"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": [
"node_modules"
]
}
h、shims-vue.d.ts
/* eslint-disable */
/**
* 1、声明.vue文件:.vue文件导出的component对象的类型是DefineComponent<{}, {}, any>
* 2、.vue文件defineComponent函数:
* - 源码:function defineComponent(options) {return options}
* - 作用:可以使options具有类型限制
*/
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
二十二、项目实战细节
1、获取组件实例的类型
<template>
<div>
<son-component ref="sonComponentRef"></son-component>
<el-button @click="clickHandler">减1按钮</el-button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import SonComponent from './son-component.vue'
export default defineComponent({
components: { SonComponent },
setup() {
const sonComponentRef = ref()
type SonComponentType = InstanceType<typeof SonComponent>
const clickHandler = () => {
/**
* 1、函数签名以new关键字为前缀:
* - var BankAccount: new() => BankAccount;
* 则BankAccount函数只能以new BankAccount()方式调用
* 2、InstanceType获取构造函数的实例类型:
* - InstanceType<typeof SonComponent>;
* 获取子组件实例的类型
*/
const sonComponentInstance: SonComponentType = sonComponentRef.value
// 3、组件实例中的属性并不是ref对象,而是proxy对象,所以不需要.value
sonComponentInstance.person.age--
}
return {
sonComponentRef,
clickHandler
}
}
})
</script>
<template>
<div>{{ person }}</div>
<el-button @click="clickHandler">加1按钮</el-button>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const person = ref({
name: '黄婷婷',
age: 18
})
const clickHandler = () => {
person.value.age++
}
return {
person,
clickHandler
}
}
})
</script>