前言
记录一下使用 Vue-Cli 创建 Vue3+TS 项目并整合 ElementPlus、Axios 等组件或插件。
一、使用 Vue-Cli 创建 Vue3+TS 项目
1.新建一个 temp 文件夹
(1)在桌面新建一个 temp 文件夹,然后在 VS Code 中打开此文件夹,打开一个终端;
(2)查看一下 node、npm、vuecli 的版本;
Windows PowerShell
版权所有 (C) Microsoft Corporation。保留所有权利。
尝试新的跨平台 PowerShell https://aka.ms/pscore6
PS C:\Users\Administrator\Desktop\temp>
PS C:\Users\Administrator\Desktop\temp> node -v
v16.17.1
PS C:\Users\Administrator\Desktop\temp> npm -v
9.2.0
PS C:\Users\Administrator\Desktop\temp> vue -V
@vue/cli 5.0.8
PS C:\Users\Administrator\Desktop\temp>
2.创建一个 Vue3 项目工程
(1)创建一个 Vue 项目,按上下方向键来选择,此处选第三个,手动选择特性,然后回车确认;
vue create vue_cli-vue3-ts-less-element_plus
Vue CLI v5.0.8
? Please pick a preset:
Default ([Vue 3] babel, eslint) // 创建一个带有babel, eslint插件的Vue 3项目
Default ([Vue 2] babel, eslint) // 创建一个带有babel, eslint插件的Vue 2项目
> Manually select features // 手动选择特性
(2)添加所需插件,按上下方向键来移动,按空格键进行选择,全部选择完了再回车确认;
Vue CLI v5.0.8
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)er> to proceed)
(*) Babel // JS编译器
(*) TypeScript // TypeScript扩展
( ) Progressive Web App (PWA) Support // 渐进式Web应用程序
(*) Router // Vue路由
(*) Vuex // Vue状态管理器
>(*) CSS Pre-processors // CSS 预处理器(如:less、sass)
( ) Linter / Formatter // 代码风格检查和格式化,这家伙太严谨了,一般不选
( ) Unit Testing // 单元测试
( ) E2E Testing // E2E(end to end)测试
(3)选择 Vue 版本,按上下方向键来选择,此处选择 3.x ,然后回车确认;
Vue CLI v5.0.8
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)? Check the features needed for your project: Babel, TS, Router, Vuex, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with (Use arrow keys)
> 3.x
2.x
(4)是否使用 Class 风格装饰器,此处输入【y】,然后回车确认;
Vue CLI v5.0.8
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)? Check the features needed for your project: Babel, TS, Router, Vuex, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with 3.x
? Use class-style component syntax? Yes
(5)Babel 和 TS 是否一起使用,用于现代模式、自动检测的 polyfills 和转译 JSX,此处输入【y】,然后回车确认;
Vue CLI v5.0.8
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)? Check the features needed for your project: Babel, TS, Router, Vuex, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with 3.x
? Use class-style component syntax? Yes
? Use Babel alongside TypeScript (required for modern mode, auto-detected polyfills, transpiling JSX)? Yes
(6)选择路由模式,此处输入【n】,即使用默认的 hash 模式,然后回车确认;
Vue CLI v5.0.8
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)? Check the features needed for your project: Babel, TS, Router, Vuex, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with 3.x
? Use class-style component syntax? Yes
? 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) (Y/n) n
(7)选择 CSS 预处理器,按上下方向键来选择,笔者习惯了 Less,然后回车确认;
Vue CLI v5.0.8
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)? Check the features needed for your project: Babel, TS, Router, Vuex, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with 3.x
? Use class-style component syntax? Yes
? 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)
> Less
Stylus
(8)Babel、ESLint 等插件的配置是单独的文件进行配置,还是都在 package.json 文件里面?此处输选择 package.json 咯,并不想太多零散的配置文件,然后回车确认;
Vue CLI v5.0.8
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)? Check the features needed for your project: Babel, TS, Router, Vuex, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with 3.x
? Use class-style component syntax? Yes
? 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): Less
? Where do you prefer placing config for Babel, ESLint, etc.?
In dedicated config files
> In package.json
(9)是否保存当前创建 Vue3 项目的特性配置,下次再创建 Vue 项目的时候,可以选择该特性,然后回车确认即可创建完成。笔者认为这个不用保存,输入【n】,然后回车确认;
Vue CLI v5.0.8
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection, and <enter> to proceed)? Check the features needed for your project: Babel, TS, Router, Vuex, CSS Pre-processors
? Choose a version of Vue.js that you want to start the project with 3.x
? Use class-style component syntax? Yes
? 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): Less
? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
? Save this as a preset for future projects? (y/N) n
(10)等待片刻,项目刷刷刷地创建完成了;
Vue CLI v5.0.8
✨ Creating project in C:\Users\Administrator\Desktop\temp\vue_cli-vue3-ts-less-element_plus.
🗃 Initializing git repository...
⚙️ Installing CLI plugins. This might take a while...
added 864 packages in 28s
91 packages are looking for funding
run `npm fund` for details
🚀 Invoking generators...
📦 Installing additional dependencies...
added 35 packages in 18s
94 packages are looking for funding
run `npm fund` for details
⚓ Running completion hooks...
📄 Generating README.md...
🎉 Successfully created project vue_cli-vue3-ts-less-element_plus.
👉 Get started with the following commands:
$ cd vue_cli-vue3-ts-less-element_plus
$ npm run serve
PS C:\Users\Administrator\Desktop\temp>
二、启动项目
(1)接着上面的步骤,在 VS Code 终端进入刚创建好的项目【vue_cli-vue3-ts-less-element_plus】的目录,以及运行一下项目;
cd vue_cli-vue3-ts-less-element_plus
npm run serve
(2)启动成功,如下所示;
DONE Compiled successfully in 3852ms 10:03:09
App running at:
- Local: http://localhost:8080/
- Network: http://IP:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
(3)在键盘按下【ctrl + c】,并输入【y】,可以停止该服务;
终止批处理操作吗(Y/N)? y
PS C:\Users\Administrator\Desktop\temp\vue_cli-vue3-ts-less-element_plus>
(4)配置支持输入【npm start】进行项目启动,在【package.json】文件加上【"start": "npm run serve"】代码,之后就可以输入【npm start】进行项目启动了,如下所示;
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"start": "npm run serve"
},
三、整合 ElementPlus 组件库
(1)具体操作如下:
第一步:导入依赖包
npm i element-plus -D
第二步:在项目的 src 目录新建 plugins 文件夹,里面再新建 element-plus.ts 文件,写入以下代码
import ElementPlus from 'element-plus'
import 'element-plus/theme-chalk/index.css'
import zhCn from 'element-plus/es/locale/lang/zh-cn' // 汉化 element-plus 组件
export default (app: any) => {
app.use(ElementPlus, {
locale: zhCn,
})
}
第三步:在项目的 main.ts 文件夹引入和使用该插件和注册图标,即整合完成,main.ts 文件如下所示
import {
createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
const app = createApp(App)
// 引入 ElementPlus 插件(npm i element-plus)
import ElementPlusPlugin from '@/plugins/element-plus'
// 全局注册 ElementPlus 图标组件(npm install @element-plus/icons-vue)
import * as ElementPlusIcons from '@element-plus/icons-vue'
for(const [key, component] of Object.entries(ElementPlusIcons)) {
app.component(key, component)
}
app
.use(store)
.use(router)
.use(ElementPlusPlugin)
.mount('#app')
第四步:验证整合成功,在项目的 App.vue 文件夹,例如写个按钮标签,保存即可看到效果,App.vue 文件如下所示
<template>
<div style="display: flex; padding: 100px; align-item: center;">
<el-button size="small" type="primary" icon="UploadFilled" @click="void (0)">
点击事件
</el-button>
<el-button size="small" type="primary" plain @click="void (0)">
<el-icon :size="18">
<UploadFilled />
</el-icon>
<span>点击事件</span>
</el-button>
<el-button size="small" type="primary" circle>
<el-icon :size="18">
<UploadFilled />
</el-icon>
</el-button>
<el-icon :size="20" style="color: #409eff; cursor: pointer" @click="void (0)">
<UploadFilled />
</el-icon>
</div>
</template>
<style lang="less">
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
border: none;
}
#app {
width: 100%;
height: 100%;
}
</style>
四、封装并使用 Axios 插件
(1)导入相关依赖,封装 axios 工具并且使用;
第一步:导入 axios 和 nprogress 依赖包
npm i axios
npm i nprogress
npm i --save-dev @types/nprogress
第二步:在 src 目录新建 utils 文件夹,再新建 requestUtil.ts 文件,写上以下代码
import axios from 'axios'
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import {
ElMessage } from 'element-plus'
const http = axios.create({
baseURL: '',
timeout: 300 * 1000, // 请求超时时间设置为300秒
})
const NETWORK_ERROR = '网络错误,请联系开发人员'
/**
* 请求拦截器
*/
http.interceptors.request.use((req) => {
console.log('请求拦截器 =>', req)
Nprogress.start()
return req;
}, (error) => {
Nprogress.done()
return Promise.reject(error);
});
/**
* 响应拦截器
*/
http.interceptors.response.use(function (res) {
console.log('响应拦截器 =>', res)
Nprogress.done()
if (res.status == 200) {
return res.data
} else {
ElMessage.error((NETWORK_ERROR))
return Promise.reject(NETWORK_ERROR)
}
});
export default http
第三步:在 src 目录新建 api 文件夹,里面再新建 UserManage 文件夹,里面再新建 index.ts 文件,写上以下代码
import http from '@/utils/requestUtil'
export default {
/**
* 根据用户ID查询用户信息
* 请服务端先准备好此接口:http://localhost:8080/v1/api/getUserById?userId=10001
*/
getUserById(userId: any) {
return http.get(`/v1/api/getUserById?userId=${
userId}`)
},
/**
* 保存用户信息
*/
saveUser(data: any) {
return http.post(
'/v1/api/saveUser',
data,
{
headers: {
'Content-Type': 'application/json'
},
}
)
},
}
第四步:在 main.ts 文件引入HTTP请求工具并配置为全局方法
// 引入HTTP请求工具并配置为全局方法
import axios from 'axios'
import UserManage_Api from '@/api/UserManage/index'
app.config.globalProperties.$http = {
...UserManage_Api,
}
app.config.globalProperties.$axios = axios
(2)接口请求示例;
第一步:在 vue.config.js 文件配置Api接口请求的服务端主机和端口,如下所示
const {
defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack(config) {
config.plugin('html').tap((args) => {
args[0].title = '帅龍之龍'
return args
})
},
devServer: {
// host: '0.0.0.0', // 主机
// port: 8080, // 端口
hot: true, // 启用热更新
https: false, // 是否开启 HTTPS 模式访问
open: false, // 当项目启动后是否立即在浏览器打开
proxy: {
// 项目 v1 的服务端接口地址
'/v1/api': {
target: 'http://127.0.0.1:8091/',
changeOrigin: true,
secure: false,
ws: true
},
// 项目 v2 的服务端接口地址
'/v2/api': {
target: 'http://127.0.0.1:8092/',
changeOrigin: true,
secure: false,
ws: true
},
// 项目 v3 的服务端接口地址
'/v3/api': {
target: 'http://127.0.0.1:8093/',
changeOrigin: true,
secure: false,
ws: true
},
// // 默认服务端接口地址
// '/': {
// target: 'http://127.0.0.1:8090/',
// changeOrigin: true,
// secure: false,
// ws: true
// }
}
}
})
第二步:在 App.vue 文件加上接口请求代码,如下所示
<template>
<div style="display: flex; padding: 100px; align-item: center;">
<el-button size="small" type="primary" icon="UploadFilled" @click="void (0)">
点击事件
</el-button>
<el-button size="small" type="primary" plain @click="void (0)">
<el-icon :size="18">
<UploadFilled />
</el-icon>
<span>点击事件</span>
</el-button>
<el-button size="small" type="primary" circle>
<el-icon :size="18">
<UploadFilled />
</el-icon>
</el-button>
<el-icon :size="20" style="color: #409eff; cursor: pointer" @click="void (0)">
<UploadFilled />
</el-icon>
</div>
</template>
<script>
export default {
data: () => ({
content: ''
}),
created() {
this.getUserById(10001)
},
methods: {
/**
* 根据用户ID查询用户信息
*/
async getUserById(userId) {
// http://127.0.0.1:8080/v1/api/getUserById?userId=10001
const res = await this.$http.getUserById(userId)
console.log(res)
},
}
}
</script>
五、项目仓库地址
到此,使用 Vue-Cli 创建 Vue3+TS 项目并整合 ElementPlus、Axios 等组件或插件的工作已全部完成,传送门如下。
六、整合其它插件
接下来可以像 Vue2 整合其他插件一样,继续整合一些需要的插件到 Vue3 项目中,例如以下文章。
基于 Vue2.X/Vue3.X 项目引入 vue-code-diff/v-code-diff 代码差异插件并使用_帅龍之龍的博客-CSDN博客_vue3引入diff库
Vue3项目打包时开启 Gzip 压缩和移动端调试时开启 vConsole 调试_帅龍之龍的博客-CSDN博客_vue3 vconsole