# vue3项目 **Repository Path**: islands_yang/vue3-web ## Basic Information - **Project Name**: vue3项目 - **Description**: No description available - **Primary Language**: Java - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-06-14 - **Last Updated**: 2024-07-10 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # vite2+vue3+ts+pinia开发日志 ## 一、 开发准备 ### 1.1、环境 ​ [Node.js](https://nodejs.org/en) ​ [Vite](https://vitejs.cn/) 需要 [Node.js](https://nodejs.org/en/) 版本>= 14.18+,16+。 ### 1.2、开发工具 [VSCode](https://code.visualstudio.com/) 所需要的插件: Vue Language Features (Volar)、TypeScript Vue Plugin (Volar)、Vue VSCode Snippets ==如果使用过vue2 装过Vetur 则需要将其禁用。== ## 二、创建项目/配置 ### 2.1、使用vite2构建工具,初始化项目 ```shell $ npm create vite@latest OR $ yarn create vite # yarn 初始化项目 # yarn dev 启动 项目 ``` ### 2.2、Vite.config.ts配置 #### 2.2.1、共享配置 ```tsx server:{ host:'0.0.0.0', //解决Network:use --host to expose port: 8080, //运行端口 open: true //是否自动打开浏览器 cors: false, //为开发服务器配置 CORS } ``` #### 2.2.2、情景(环境)配置 1. .env 文件创建在 vue 项目的根目录下,和 package.json同级 ```tsx .env //所有情况下都会加载 .env.local //所有情况下都会加载,但会被 git 忽略 .env.[mode] //只在指定模式下加载 .env.[mode].local //只在指定模式下加载,但会被 git 忽略 //案例 VITE_HOST = '172.20.25.155' //地址 VITE_PORT = 8080 //端口 VITE_BASE_URL = './' VITE_OUTPUT_DIR = 'dist' VITE_API_DOMAIN = 'http://10.1.1.111:8080/api/'//本地环境地址(可用于开发时联调) ``` ​ 2.配置运行环境,在 package.json ```json "scripts": { // "dev": "vite", // "build": "vue-tsc && vite build", // "preview": "vite preview", "dev": "vite serve --mode dev", //执行dev环境 "build": "vue-tsc --noEmit && vite build --mode prop", //执行 build 打包prop环境 "prop": "vite serve --mode prop" //执行线上环境 }, ``` ​ 3.使用 ```tsx import { loadEnv,defineConfig } from 'vite'; /** * process会报错,需要安装 cnpm i --save-dev @types/node * 异步函数,获取本地文件 * @param mode * @returns */ function asyncFunction(mode) { // 根据当前工作目录中的 `mode` 加载 .env 文件 // 设置第三个参数为 '' 来加载所有环境变量,而不管是否有 `VITE_` 前缀。 const env = loadEnv(mode, process.cwd(), ''); return env; } 调用 asyncFunction()方法,返回 环境变量 //如: import { loadEnv,defineConfig } from 'vite' //安装 cnpm i --save-dev @types/node export default defineConfig(async ({ command, mode }) => { const env = await asyncFunction(mode); return { plugins: [vue()], server: { host: '0.0.0.0', port: Number(env.VITE_HOST), open: true,css预处理器 } // vite 配置 } }); ``` #### 2.2.3、别名配置 ```tsx //安装依赖 cnpm install @types/node --save-dev //配置vite.config.ts export default defineConfig(async ({ command, mode }) => { return { resolve:{ alias:[ { find: '@', replacement: resolve(__dirname, '/src') }, ] } } }); //配置tsconfig.json "compilerOptions":{ "baseUrl": ".", "paths": { "@/*": [ "src/*" ] } } ``` ## 三、项目集成组件 ### 3.1、css预处理器 ```shell cnpm i node-sass -D #安装sass或less cnpm install -D sass-loader OR cnpm install -D less ``` ```tsx //解决 export default defineConfig(async ({ command, mode }) => { return { //这个节点,用于配置所有第三方模块加载器 module: { rules: [ //所有第三方模块的匹配规则 //配置处理.scss文件的第三方loader规则 { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'] }, ] }, } }); ``` ​ ```tsx export default defineConfig(async ({ command, mode }) => { return { css: { preprocessorOptions: { scss: { additionalData: `$injectedColor: orange;` }, styl: { additionalData: `$injectedColor ?= orange` } } }, } }); ``` ### 3.2、[ESLint](http://eslint.cn/)代码检查工具 #### 3.2.1、为什么要用eslint? - 统一团队编码规范 - 统一语法(比如变量是用var/let) - 减少git不必要 的提交 - 避免低级错误 - 在 编译时检查语法,而不是等JS引擎运行时才检查 #### 3.2.2、安装 ```shell $ npm install eslint --save-dev ``` #### 3.2.3、使用 ```tsx // 在根目录下创建 .eslintrc.js module.exports = { root: true, //环境 浏览器,最新es语法,node环境 env: { browser: true, node: true, es6: true, }, //扩展 的eslint规范语法,可以被继承的规则;字符串数组:每个配置继承它前面的配置 extends: [ "plugin:vue/vue3-essential", "eslint:recommended", "@vue/typescript/recommended", "@vue/prettier", "@vue/prettier/@typescript-eslint", "eslint:all", 'alloy/typescript', ], //eslint 会对我们的代码进行校验,而parser的作用时将我们的代码转为ESTree,ESLint会对ESTree进行校验 parser: "vue-eslint-parser", //解析器的配置项 parserOptions: { ecmaVersion: 2022, // es版本号/年份都可以 parser: "@typescript-eslint/parser", sourceType: "module" // 默认为script,使用es6 module设置为module }, //自定义规则 rules: { "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off", "no-irregular-whitespace": ["on"], // 取消空格报错 "no-unused-vars": "off", // 定义了或者声明引入了,但没有使用不报错 "@typescript-eslint/no-unused-vars": ["off"], //没有使用的参数,不会报错。因为个人觉的把可用的参数写上去 有利于以后的维护。 "@typescript-eslint/no-empty-function": ["off"], // 方法内部没有逻辑书写,不会报错,可以先定义好方法名,方便使用 "@typescript-eslint/no-explicit-any": ["off"], // ts 定义数据类型为any不报错 }, }; ``` ## 四、UI框架 ### 4.1、[ElementUI](https://element-plus.org/zh-CN/) #### 4.1.1、安装 ```shell $ yarn add element-plus OR $ npm install element-plus --save ``` #### 4.1.2、引入 ```tsx //1.全局引入(不推荐) // 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'); //如果您使用 Volar,请在 tsconfig.json 中通过 compilerOptions.type 指定全局组件类型 { "compilerOptions": { // ... "types": ["element-plus/global"] } } //2.按需引入(推荐) // 安装 npm install -D unplugin-vue-components unplugin-auto-import // 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()], }), ], }) ``` ## 五、轻量级状态管理库 ### 5.1、[pinia](https://pinia.web3doc.top) #### 5.1.1、安装Pinia ```shell yarn add pinia@next OR npm install pinia@next ``` #### 5.1.2、引入 ```tsx import { createPinia } from "pinia"; //创建pinia实例 const pinia = createPinia() app.use(pinia); //创建文件 1.在src目录下创建本地缓存文件 store 2.在store目录中创建所需要的缓存XX.ts(如) import { defineStore } from 'pinia' export const useTodoStore = defineStore('todo', { state: () => { return{ count: 0 } }, getters: { double: (state) => state.count * 2, }, actions: { increment() { this.count++ }, }, }) 3.在需要的地方引入即可 4.结构 pinia 需要引入 import {storeToRefs} from 'pinia'; ``` #### 5.2、[vuex](https://vuex.vuejs.org) 5.2.1、安装vuex ```shell $ npm install vuex@next --save OR $ yarn add vuex@next --save ``` ## 六、[Router](https://router.vuejs.org/zh/installation.html) ### 6.1、安装 ```shell $ npm install vue-router@4 OR $ yarn add vue-router@4 ``` ### 6.2、全局注册 ```tsx //1.创建路由文件 src/router/index.ts import { createRouter, createWebHistory, RouteRecordRaw, createWebHashHistory } from "vue-router"; //路由列表数组 export const routes: Array = [ { path:'/', name:'home', component:'' } ] //创建路由 const router = createRouter({ history: createWebHistory(), routes }) //导出使用 export default router //2. 全局注册 //main.ts import router form './router/index'; const app = createApp(App) app.use(router) //3.使用 在需要使用的地方插入下面两个标签中的一个,根据情况 自定义组件 router-link 来创建链接 router-view 将显示与 url 对应的组件。你可以把它放在任何地方,以适应你的布局 ``` ## 七、国际化[[Vue I18n](https://kazupon.github.io/vue-i18n/zh/)] ### 7.1、安装 ```shell $ yarn add vue-i18n@next OR $ npm install vue-i18n ``` ### 7.2、引入/使用 ```tsx //1.新建 i18n目录 index.ts // 国际化配置文件出口 import { createI18n } from "vue-i18n"; //创建对应语言文件,导出 import zh from '@/i18n/zh-CN/index' import en from '@/i18n/en-US/index' const i18n = createI18n({ legacy: false, // 修复组件引入i18n时vite脚手架报错的问题 locale: 'zh', //默认语言 fallbackLocale: 'zh',// 不存在默认则为中文 allowComposition: true,// 允许组合式api globalInjection: true, // 全局注入 $t 函数 silentTranslationWarn: true, // 去掉警告 silentFallbackWarn: true, //抑制警告 missingWarn: false, sync: true, messages: { zh: zh, en: en, }, }); export default i18n; //2.main.ts 中全局引入 import { createApp } from 'vue'; import App from '@/App.vue'; import i18n from '@/i18n/index' const app = createApp(App) app.use(i18n) .mount('#app') //3.切换语言方法 import { useI18n } from 'vue-i18n'; const { locale } = useI18n(); locale.value="对应语言出口值" //4.语法 详见官网 ``` ## 八、主题 ## 九、动画效果 ### 9.1、[Animate](https://animate.style) #### 9.1.1、安装 ```shell $ npm install animate.css --save OR $ yarn add animate.css ``` #### 9.1.2、引入 ```tsx import 'animate.css';

An animated element

``` ## 十、图标库 ### 10.1、[字节跳动图标库](https://iconpark.oceanengine.com/official) #### 10.1.1、安装 ```shell $ cnpm i @icon-park/vue ```