Vue 3 + TypeScript + Vite+ VueRouter + Axios + ElementPlus + Sass

创建 Vite 项目

普通创建

npm createnpm init 的别名

1
2
3
4
5
6
7
8
// NPM
npm create vite@latest

// Yarn
yarn create vite

// PNPM
pnpm create vite

模板创建

1
2
3
4
5
6
7
8
9
10
11
// npm 6.x
npm create vite@latest my-vue-app --template vue

// npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue

// yarn
yarn create vite my-vue-app --template vue

// pnpm
pnpm create vite my-vue-app --template vue

查看 create-vite 以获取每个模板的更多细节:vanillavanilla-tsvuevue-tsreactreact-tspreactpreact-tslitlit-tssveltesvelte-ts

1
2
// 我这里是用的 vue3 + ts
npm create vite@latest my-vue-app -- --template vue-ts

安装依赖

1
npm install

运行

1
npm run dev

使用@路径的别名配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// vite.config.ts
import { resolve } from 'path' // 如果有波浪线 因为引入了path包,项目又使用ts功能,所以我们需要安装node的ts解析文件(npm i -D @types/node)再不行就重启vscode

export default defineConfig({
//....
resolve: {
//alias: {
// '@': path.resolve(__dirname, 'src')
//}
alias: [//配置别名
{
find: '@', replacement: resolve(__dirname, './src')
}
],
},
//....
});
1
2
3
4
5
6
7
8
9
10
11
// 配置了别名 tsconfig.json 里面也要加上
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
},
// ...
}

配置本地服务器

1
2
3
4
5
6
7
8
9
10
// vite.config.ts
export default defineConfig({
//....
server: {
host: 'localhost', //ip
port: 8080, //端口号
strictPort: false, // 为 true 时若端口已被占用则会直接退出,而不是尝试下一个可用端口
}
//....
});

使用 ElementPlus

安装

1
2
3
4
5
6
7
8
// NPM
npm install element-plus --save

// Yarn
yarn add element-plus

// pnpm
pnpm install element-plus

完整引入

1
2
3
4
5
6
7
8
9
10
// main.ts
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'

const app = createApp(App)

app.use(ElementPlus)
app.mount('#app')

按需引入

您需要使用额外的插件来导入要使用的组件

自动导入(推荐)

首先你需要安装unplugin-vue-componentsunplugin-auto-import这两款插件

1
npm install -D unplugin-vue-components unplugin-auto-import

然后把下列代码插入到你的 Vite 的配置文件中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// vite.config.ts
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

export default defineConfig({
// ...
plugins: [
// ...
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
})
手动导入

需要安装 unplugin-element-plus 来导入样式。 请参考 文档 了解如何配置它

1
2
3
4
5
6
7
8
9
<template>
<el-button>I am ElButton</el-button>
</template>
<script>
import { ElButton } from 'element-plus'
export default {
components: { ElButton },
}
</script>
1
2
3
4
5
6
7
8
// vite.config.ts
import { defineConfig } from 'vite'
import ElementPlus from 'unplugin-element-plus/vite'

export default defineConfig({
// ...
plugins: [ElementPlus()],
})

使用 SASS

安装

1
npm install --save-dev sass

编写全局css变量/全局mixin

1
2
3
4
// 全局变量 / globalVar.scss
$font-size-normal: 32px;

$bg-color: #1989fa;
1
2
3
4
5
6
// 全局mixin / globalMixin.scss
@mixin box-shadow($bulr: 20px, $color: #1989fa7a) {
-webkit-box-shadow: 0px 0px $bulr $color;
-moz-box-shadow: 0px 0px $bulr $color;
box-shadow: 0px 0px $bulr $color;
}

vite引入并使用

1
2
3
4
5
6
7
8
9
10
11
12
13
// vite.config.ts
//全局引入
css: {
preprocessorOptions: {
scss: {
/**如果引入多个文件,可以使用
* '@import "@/assets/scss/globalVariable1.scss";
* @import"@/assets/scss/globalVariable2.scss";'
**/
additionalData: '@import "@/styles/globalVar.scss";',
}
}
},
1
2
3
4
5
6
7
8
9
10
11
<!-- 按需引入并使用 -->
<style scoped lang="scss">
@import "@/styles/globalMixin.scss";
.test{
width: 650px;
height: 60px;
font-size: $font-size-normal;
background-color: $bg-color;
@include box-shadow;
}
</style>

使用 VueRouter

安装

1
npm install vue-router@4

创建路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//   src/router/index.ts

import { createRouter, RouteRecordRaw, createWebHashHistory } from 'vue-router';
// import { createWebHistory } from 'vue-router'

import HomeView from '../views/HomeView.vue';

const routes: Array<RouteRecordRaw> = [
{
path: '/',
redirect: '/home',
},
{
path: '/home',
name: 'home',
component: HomeView,
},
];

const router = createRouter({
// history: createWebHistory(process.env.BASE_URL), // history模式
history: createWebHashHistory(), // hash模式
routes,
});

export default router;

引入使用

1
2
3
4
5
6
7
8
9
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(router)
app.mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script setup lang="ts">
import { useRouter } from 'vue-router';

const router = useRouter();

const fn = function () {
router.push('/abc')
}
</script>

<template>
<button @click="fn">编程式导航</button>
<router-link to="/home">路由组件导航</router-link>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</template>

使用 Vuex

安装

1
2
3
4
5
// npm
npm install vuex@next --save

// Yarn
yarn add vuex@next --save

创建 Store (状态管理库)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/store/index.ts
import { createStore } from 'vuex'

// 创建一个新的 store 实例 并导出
export default createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
}
})

引入使用

1
2
3
4
5
6
7
8
9
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)

app.use(store)
app.mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12
<script setup lang="ts">
import { useStore } from 'vuex';
const store = useStore();
const fn = function () {
store.commit('increment');
};
</script>

<template>
<button @click="fn">按钮</button>
<p>{{ store.state.count }}</p>
</template>

使用 Axios

安装

1
2
3
4
5
6
7
8
// npm
npm install axios

// bower
bower install axios

// yarn
yarn add axios

封装axios请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// src/utils/request.ts

import axios from 'axios';

const request = axios.create({
// baseURL: 'http://localhost:3006' 请求地址
// timeout: 1000 // 超时时间
});

// 添加请求拦截器
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
}
);

// 添加响应拦截器
axios.interceptors.response.use(
function (response) {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response;
},
function (error) {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
}
);

export default request;
1
2
3
4
5
6
7
8
9
// src/api/cs.ts
import request from '@/utils/request';

export function getCS() {
return request({
method: 'get',
url: '/cs',
});
}

使用

1
2
3
4
5
6
7
8
9
10
11
<script setup lang="ts">
import { getCS } from '@/api/cs';

const getData = function () {
getCS()
};
</script>

<template>
<button @click="getData">发送请求</button>
</template>

使用 eslint

安装

1
2
// npm
npm install eslint --save-dev

初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
npx eslint --init

// 你也可以直接使用'npm init @eslint/config'来运行这个命令。
You can also run this command directly using 'npm init @eslint/config'.
? How would you 1ike to use ESLint? ..- // 你想如何使用ESLint?
To check syntax only // 只检查语法
To check syntax and find problems // 检查语法并发现问题
> To check syntax,find problems,and enforce code style // 检查语法、发现问题和执行代码样式
? what type of modules does your project use? . // 您的项目使用什么类型的模块?
> JavaScript modules (import/export)
CommonJS (require/exports)
None of these // 这些都不是
? Which framework does your project use? // 您的项目使用哪个框架?
React
> Vue.js
None of these
? Does your project use TypeScript? No / Yes // 你的项目使用TypeScript吗? yes
? Mhere does your code run? ... (Press 〈space> to select,<a> to toggle all, is to invert selection) // 代码在哪里运行?... (按<空格>选择,<a>切换全部,<i>反转选择n)
Browser // √
Node // √
? How would you like to define a style for your project? // 你想如何为你的项目定义一个风格?
> Use a popular style guide // 使用流行的风格指南
Answer questions about your style // 回答关于你的风格的问题
? Which style guide do you want to fo11ow?. // 你想遵循哪一个风格指南?
> Standard: https://github.com/standard/eslint-config-standard-with-typescript // 标准规范
XO: https://github.com/xojs/eslint-config-xo-typescript
? What format do you want your config file to be in? // 您希望配置文件的格式是什么?
> JavaScript
YAML
JSON
"Checking peerDependencies of eslint-config-standard-with-typescript@latestThe config that you've selected requires the following dependencies:" // 检查eslint-config-standard-with-typescript@latest的peerDependencies,您所选择的配置需要以下依赖项:

eslint-plugin-vue@latest eslint-config-standard-with-typescript@latest @typescript-eslint/eslint-plugin@^5.0.0 eslint@^8.0.1 eslint-plugin-import@^2.25.2 eslint-plugin-n@15.0.0 eslint-plugin-promise6.0.0 typescript@*
? would you like to install them now? No / Yes // 您想现在安装它们吗? yes
? which package manager do you want to use? // 您想使用哪个包管理器?
> npm
yarn
pnpm

"Installing eslint-plugin-vue@latest,eslint-config-standard-with-typescript@latest,@typescript-eslint/eslint-plugin@^5.0.0,eslint@^8.0.1,eslint-plugin-import@'2.25.2, eslint-plugin-n@^15.0.0, eslint-plugin-promise@~6.0.0,typescript@*"

added 97 packages,and changed 1 package in 19s // 增加了97个包,在19s中改变了1个包
Successfully created .eslintrc.cjs file in C:\Users \admin\Desktop\vite-vue-ts // 成功在C:(Users(admin(Desktop(vitve -vue-ts))中创建.eslintrc.cjs文件

配置默认格式化程序

1
搜索设置框贴入editor.defaultFormatter

目录结构

使用一个Node模块来自动完成这个任务:mddir

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 1.安装mddir包
npm install mddir -D

// 2. 打开终端或命令提示符,并cd进入mddir /src文件夹
cd node_modules/mddir/src

// 3.运行命令生成到当前文件夹
node mddir "../../../"

// 4.directoryList.md ( 目前忽略node_modules和.git文件夹。)

|-- undefined
|-- .gitignore
|-- index.html
|-- package-lock.json
|-- package.json
|-- README.md
|-- tsconfig.json
|-- tsconfig.node.json
|-- vite.config.ts
|-- .vscode
| |-- extensions.json
|-- public
| |-- vite.svg
|-- src
|-- App.vue
|-- main.ts
|-- style.css
|-- vite-env.d.ts
|-- assets
| |-- vue.svg
|-- components
| |-- HelloWorld.vue
|-- router
| |-- index.ts
|-- styles
| |-- globalMixin.scss
| |-- globalVar.scss
| |-- theme
|-- views
|-- HomeView.vue