使用 Vue-Cli 创建 Vue3+TS 项目并整合 ElementPlus、Axios 等组件或插件

简介: 本文详细记录了如何使用Vue-Cli工具创建一个Vue3+TypeScript项目,并整合ElementPlus组件库和Axios等插件,包括项目的创建、配置、启动和插件封装使用等步骤。

前言

记录一下使用 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 等组件或插件的工作已全部完成,传送门如下。

vue_cli-vue3-ts-less-element_plus: 这是一个基于 Vue-Cli 构建的 Vue3 + TS 项目,以及整合了 Less、Axios、ElementPlus 等组件或插件。

六、整合其它插件

接下来可以像 Vue2 整合其他插件一样,继续整合一些需要的插件到 Vue3 项目中,例如以下文章。

基于 Vue2.X/Vue3.X 项目引入 vue-code-diff/v-code-diff 代码差异插件并使用_帅龍之龍的博客-CSDN博客_vue3引入diff库

Vue3项目打包时开启 Gzip 压缩和移动端调试时开启 vConsole 调试_帅龍之龍的博客-CSDN博客_vue3 vconsole

基于Vue2.X对WangEditor 5富文本编辑器进行封装与使用,支持单个或多个图片点击、粘贴、拖拽上传,Vue3.X项目也可直接使用_帅龍之龍的博客-CSDN博客_wangeditor5 自定义粘贴

Vue3项目引入 vue-quill 编辑器组件并封装使用_帅龍之龍的博客-CSDN博客_vue3使用vuequill

目录
相关文章
|
22天前
|
JSON JavaScript 前端开发
【Vue面试题二十四】、Vue项目中有封装过axios吗?主要是封装哪方面的?
这篇文章讨论了在Vue项目中封装axios的最佳实践,包括设置接口请求前缀、请求头、状态码、请求方法的封装,以及如何使用请求和响应拦截器来处理token和响应状态,从而简化HTTP请求的配置和错误处理,提高代码的可维护性。
【Vue面试题二十四】、Vue项目中有封装过axios吗?主要是封装哪方面的?
|
27天前
|
JavaScript C++
使用 Vite 创建 Vue3+TS 项目并整合 ElementPlus、Axios、Pinia、Less、Vue-router 等组件或插件
本文详细介绍了如何使用Vite创建Vue3+TypeScript项目,并整合ElementPlus、Axios、Pinia、Less、Vue-router等组件或插件的步骤和配置方法。
207 1
|
4月前
|
JavaScript
vue封装axios(用interceptors封装)
vue封装axios(用interceptors封装)
46 0
|
4月前
|
JSON 前端开发 JavaScript
3分钟让你学会axios在vue项目中的基本用法(建议收藏)
3分钟让你学会axios在vue项目中的基本用法(建议收藏)
358 0
|
22天前
|
JavaScript 前端开发
【Vue面试题二十五】、你了解axios的原理吗?有看过它的源码吗?
这篇文章主要讨论了axios的使用、原理以及源码分析。 文章中首先回顾了axios的基本用法,包括发送请求、请求拦截器和响应拦截器的使用,以及如何取消请求。接着,作者实现了一个简易版的axios,包括构造函数、请求方法、拦截器的实现等。最后,文章对axios的源码进行了分析,包括目录结构、核心文件axios.js的内容,以及axios实例化过程中的配置合并、拦截器的使用等。
【Vue面试题二十五】、你了解axios的原理吗?有看过它的源码吗?
|
22天前
|
JavaScript 前端开发
【Vue面试题二十七】、你了解axios的原理吗?有看过它的源码吗?
文章讨论了Vue项目目录结构的设计原则和实践,强调了项目结构清晰的重要性,提出了包括语义一致性、单一入口/出口、就近原则、公共文件的绝对路径引用等原则,并展示了单页面和多页面Vue项目的目录结构示例。
|
2天前
|
JavaScript 前端开发 开发者
vue中使用axios请求post接口,请求会发送两次
vue中使用axios请求post接口,请求会发送两次
|
1月前
|
JavaScript 前端开发
vue引入axios出现Module parse failed: Unexpected token (5:2)
vue引入axios出现Module parse failed: Unexpected token (5:2) 页面显示 Cannot GET /
|
2月前
|
前端开发 JavaScript 数据库
vue 使用 async 和 await 实现异步 axios 同步化(实战案例:数据异步校验通过后,再执行保存)
vue 使用 async 和 await 实现异步 axios 同步化(实战案例:数据异步校验通过后,再执行保存)
48 1
|
2月前
|
JSON JavaScript 前端开发
Vue中的axios深度探索:从基础安装到高级功能应用的全面指南
在Vue项目中,高效的前后端通信是构建丰富用户体验的关键。axios作为前端与后端沟通的桥梁,其重要性不言而喻。本文将带您领略axios的魅力,从基本概念、安装方法,到高级应用技巧,助您快速掌握在Vue中利用axios进行HTTP请求的精髓。我们不仅会探讨axios的基础用法,如GET、POST请求,还将深入探索跨域配置、全局注册以及设置拦截器等高级功能,助您轻松实现优雅的前后端通信。