使用Vue Cli创建Vue3+TS项目并整合Element Plus框架以及封装使用Axios插件

一、使用Vue Cli创建Vue3+TS项目

1、在桌面新建一个temp文件夹,然后在VS Code打开,打开一个终端,查看一下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、创建一个 Vue 项目,按上下方向键来选择,此处选第三个,手动选择特性,然后回车确认;

vue create 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		// 手动选择特性

3、添加所需插件,按空格键进行选择,然后回车确认;

Vue CLI v5.0.8
? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  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 // 代码风格检查和格式化,这家伙太严谨了,一般不选(如:ESlint)
 ( ) Unit Testing // 单元测试
 ( ) E2E Testing // E2E(end to end)测试

4、选择Vue版本,按上下方向键来选择,此处选择 3.x ,然后回车确认;

Vue CLI v5.0.8
? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  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 

5、是否使用Class风格装饰器,此处输入 y,然后回车确认;

Vue CLI v5.0.8
? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  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

6、是否使用Babel和TS,此处输入 y,然后回车确认;

Vue CLI v5.0.8
? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  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

7、选择路由模式,此处输入 n,即使用默认的 hash 模式,然后回车确认;

Vue CLI v5.0.8
? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  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

8、选择CSS预处理器,按上下方向键来选择,笔者习惯用Less,无所谓咯,然后回车确认;

Vue CLI v5.0.8
? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  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

9、Babel、ESLint等插件的配置是单独的文件进行配置,还是都在package.json文件里面,此处输选择package.json咯,并不想太多零散的配置文件,然后回车确认;

Vue CLI v5.0.8
? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  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

10、是否保存当前创建Vue项目的配置信息,下次再创建Vue项目的时候,可以选择该特性,回车确认即可创建,那就保存一下咯;

Vue CLI v5.0.8
? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  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) y

11、对创建Vue项目的配置信息进行保存,以便下次选择,输入名称,然后回车确认;

Vue CLI v5.0.8
? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  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? Yes
? Save preset as: vue3_ts_less_element_plus

12、等待片刻,项目刷刷刷地创建完成了;

Vue CLI v5.0.8
✨  Creating project in C:\Users\Administrator\Desktop\temp\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 vue3_ts_less_element_plus.
  Get started with the following commands:

 $ cd vue3_ts_less_element_plus
 $ npm run serve

PS C:\Users\Administrator\Desktop\temp>

二、整合Element Plus框架

1、接以上的步骤,在VS Code终端进入刚创建好的项目 vue3_ts_less_element_plus 的目录,以及运行一下项目;

cd vue3_ts_less_element_plus
npm run serve

 启动成功如下所示

 DONE  Compiled successfully in 4852ms                                                                              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.

2、在键盘按下ctrl + c,并输入 y,可以停止该服务;

终止批处理操作吗(Y/N)? y
PS C:\Users\Administrator\Desktop\temp\vue3_ts_less_element_plus> 

3、配置支持输入 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"
},

 启动成功如下所示

PS C:\Users\Administrator\Desktop\temp\vue3_ts_less_element_plus> npm start

 INFO  Starting development server...

 DONE  Compiled successfully in 2891ms                                                                              10:13:51

  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.

4、 整合Element Plus框架;

第一步:导入依赖包
npm i element-plus

第二步:在项目的 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 文件如下所示



三、封装使用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查询用户信息
   */
  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 文件加上接口请求代码,如下所示





到此,使用VS Code创建Vue3+TS项目并整合Element Plus框架以及封装使用Axios插件的工作已全部完成。接下来就像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

你可能感兴趣的:(Vue,vue.js)