Vite+Vue3.0+ElementPlus + axios +TS 搭建项目

Vite+Vue3.0+ElementPlus + axios +TS 搭建项目

一、vite构建项目 官网

1、创建项目
// pnpm
pnpm create vite

// npm 
npm create vite@latest

// yarn
yarn create vite
2、步骤

请添加图片描述请添加图片描述
请添加图片描述
请添加图片描述

二、代码规范

注释:配置完成后需要重新启动项目

1、配置eslint
  • 安装ESlint插件
    请添加图片描述

  • 在项目根目录下找到并打开 .eslintrc.cjs 文件

    /* eslint-env node */
    require('@rushstack/eslint-patch/modern-module-resolution')
    
    module.exports = {
      root: true,
      extends: [
        'plugin:vue/vue3-essential',
        'eslint:recommended',
        '@vue/eslint-config-typescript/recommended',
        '@vue/eslint-config-prettier'
      ],
      env: {
        'vue/setup-compiler-macros': true
      },
      parserOptions: {
        ecmaVersion: 'latest'
      },
      parser: 'vue-eslint-parser',
      rules: {
        /* 
        "off" 或 0 - 关闭规则
        "warn" 或 1 - 打开规则作为警告(不影响退出代码)
        "error" 或 2 - 打开规则作为错误(触发时退出代码为 1)
        */
        'array-bracket-spacing': [2, 'never'], // 在数组括号内强制保持一致的间距
        'block-spacing': [2, 'always'], // 在打开块之后和关闭块之前禁止或强制块内的空格
        'brace-style': [2, '1tbs'], // 对块执行一致的大括号样式
        'comma-dangle': [2, 'never'], // 不允许尾随逗号
        'comma-spacing': [
          2,
          {
            before: false,
            after: true
          }
        ], // 在逗号前后强制保持一致的间距
        'comma-style': [2, 'last'], // 强制使用一致的逗号样式
        'consistent-return': [
          2,
          {
            treatUndefinedAsUnspecified: true
          }
        ], // 要求 return 语句始终或从不指定值
        'computed-property-spacing': [2, 'never'], // 在计算的属性括号内强制执行一致的间距
        'constructor-super': 2, // 在构造函数中需要 super() 调用
        curly: 2, // 强制所有控制语句使用一致的括号风格
        'default-case': 2, // 在 switch 语句中需要 default 个案例
        'eol-last': [2, 'always'], // 在文件末尾要求或禁止换行
        'func-call-spacing': [2, 'never'], // 要求或不允许函数标识符及其调用之间有间距
        'guard-for-in': 2, // 要求 for-in 循环包含 if 语句
        indent: [
          2,
          2,
          {
            SwitchCase: 1
          }
        ], // 强制一致的缩进
        'jsx-quotes': [2, 'prefer-double'], // 强制在 JSX 属性中一致地使用双引号或单引号
        'key-spacing': [
          2,
          {
            beforeColon: false,
            afterColon: true
          }
        ], // 在对象字面属性中强制键和值之间的间距一致
        'new-cap': 0, // 设置名字首字母为大写的函数可以不为构造函数
        'new-parens': 2, // 在调用不带参数的构造函数时强制或禁止使用括号
        'no-case-declarations': 2, // 不允许在case/default子句中使用词法声明
        'no-class-assign': 2, // 不允许重新分配类成员
        'no-compare-neg-zero': 2, // 禁止与 -0 进行比较
        'no-cond-assign': [2, 'always'], // 禁止条件语句中出现赋值操作符
        'no-console': 0, // 允许出现console
        'no-const-assign': 2, // 建议使用const
        'no-constant-condition': 2, // 禁止在条件中使用常量表达式
        'no-control-regex': 2, // 禁止在正则表达式中使用控制字符
        'no-debugger': 0, // 可以使用debugger
        'no-delete-var': 2, // 不允许删除变量
        'no-dupe-args': 2, // 禁止 function 定义中出现重名参数
        'no-dupe-class-members': 2, // 禁止重复的类成员
        'no-dupe-keys': 2, // 禁止对象字面量中出现重复的 key
        'no-duplicate-case': 2, // 禁止出现重复的 case 标签
        'no-empty': 2, // 禁止出现空语句块
        'no-empty-character-class': 2, // 禁止在正则表达式中使用空字符集
        'no-empty-pattern': 2, // 禁止空的解构模式
        'no-ex-assign': 2, // 禁止对 catch 子句的参数重新赋值
        'no-extra-boolean-cast': 2, // 禁止不必要的布尔转换
        'no-extra-parens': [2, 'functions'], // 禁止不必要的括号
        'no-extra-semi': 2, // 禁止不必要的分号
        'no-fallthrough': 2, // 不允许 case 语句的失败
        'no-func-assign': 2, // 禁止对 function 声明重新赋值
        'no-global-assign': [
          2,
          {
            exceptions: []
          }
        ], // 不允许分配给原生对象或只读全局变量
        'no-inner-declarations': 0, // 禁止在嵌套的块中出现变量声明或 function 声明
        'no-invalid-regexp': 2, // 禁止 RegExp 构造函数中存在无效的正则表达式字符串
        'no-irregular-whitespace': 2, // 禁止不规则的空白
        'no-mixed-spaces-and-tabs': 2, // 不允许使用混合空格和制表符进行缩进
        'no-multi-assign': 2, // 禁止使用链式赋值表达式
        'no-multiple-empty-lines': 2, // 禁止多个空行
        'no-new-symbol': 2, // 禁止带有 Symbol 对象的 new 运算符
        'no-obj-calls': 2, // 禁止把全局对象作为函数调用
        'no-octal': 2, // 禁止八进制字面
        'no-prototype-builtins': 2, // 禁止直接调用 Object.prototypes 的内置属性
        'no-redeclare': 2, // 禁止变量重新声明
        'no-regex-spaces': 2, // 禁止正则表达式字面量中出现多个空格
        'no-self-assign': 2, // 禁止两边完全相同的赋值
        'no-sparse-arrays': 2, // 禁用稀疏数组
        'no-template-curly-in-string': 0, // 禁止在常规字符串中出现模板字面量占位符语法
        'no-this-before-super': 2, // 在构造函数中调用 super() 之前禁止 this/super
        'no-undef': 0, // 除非在 /*global */ 注释中提及,否则不允许使用未声明的变量
        'no-undefined': 0, // 禁止使用 undefined 作为标识符
        'no-unexpected-multiline': 2, // 禁止出现令人困惑的多行表达式
        'no-unreachable': 2, // 禁止在 return、throw、continue 和 break 语句之后出现不可达代码
        'no-unsafe-finally': 2, // 禁止在 finally 语句块中出现控制流语句
        'no-unsafe-negation': 2, // 禁止对关系运算符的左操作数使用否定操作符
        'no-unused-labels': 2, // 禁止未使用的标签
        'no-use-before-define': 2, // 在定义之前禁止使用变量
        'no-useless-escape': 2, // 禁止不必要的转义字符
        'no-var': 2, // 禁止使用var
        'prefer-const': 2, // 声明后从不重新分配的变量需要 const 声明
        quotes: 0, // 双引号可无
        'require-yield': 2, // 要求生成器函数包含 yield
        semi: 0, // 句尾省略分号
        'space-before-function-paren': 0, // 在函数括号之前不使用间距
        strict: 2, // 要求或禁止严格模式指令
        'use-isnan': 2, // 要求使用 isNaN() 检查 NaN
        'valid-jsdoc': 0, // 强制执行有效且一致的 JSDoc 注释
        'valid-typeof': 2, // 强制 typeof 表达式与有效的字符串进行比较
        'vue/html-self-closing': [
          2,
          {
            html: {
              void: 'always',
              normal: 'always',
              component: 'always'
            },
            svg: 'always',
            math: 'always'
          }
        ] // 设置自闭合标签
      }
    }
    
  • 根目录创建忽略文件:.eslintignore

    node_modules/
    dist/
    index.html
    
  • git Husky

    husky是一个git hook工具,可以帮助我们触发git提交的各个阶段:pre-commit、commit-msg、pre-push

    • 自动配置命令

      npm install husky-init //安装husky-init包
      npx husky-init  //执行文件
      
    • 在 .husky/pre-commit 文件中修改成 npm run lint

      #!/usr/bin/env sh
      . "$(dirname -- "$0")/_/husky.sh"
          
      npm run lint 
      
    • 安装husky报错(遇到的问题)

      husky - can't create hook, .husky directory doesn't exist (try running husky install)
      
      不能创建钩子,.husky目录不存在(尝试运行Husky install)
      
    • 重新执行下面命令

      git init
      npx husky-init
      
2、配置prettier
  • 安装 Prettier 扩展
    请添加图片描述

  • 在项目根目录下找到 .prettierrc.json 文件,将其改为 .prettierrc.js 文件

    module.exports = {
      overrides: [
        {
          files: '.prettierrc',
          options: {
            parser: 'json'
          }
        }
      ],
      printWidth: 100, // 一行最多 100 字符
      tabWidth: 2, // 使用 2 个空格缩进
      semi: false, // 句尾省略分号
      singleQuote: true, // 使用单引号而不是双引号
      useTabs: false, // 用制表符而不是空格缩进行
      quoteProps: 'as-needed', // 仅在需要时在对象属性两边添加引号
      jsxSingleQuote: false, // 在 JSX 中使用单引号而不是双引号
      trailingComma: 'none', // 末尾不需要逗号
      bracketSpacing: true, // 大括号内的首尾需要空格
      bracketSameLine: false, // 将多行 HTML(HTML、JSX、Vue、Angular)元素反尖括号需要换行
      arrowParens: 'always', // 箭头函数,只有一个参数的时候,也需要括号 avoid
      rangeStart: 0, // 每个文件格式化的范围是开头-结束
      rangeEnd: Infinity, // 每个文件格式化的范围是文件的全部内容
      requirePragma: false, // 不需要写文件开头的 @prettier
      insertPragma: false, // 不需要自动在文件开头插入 @prettier
      proseWrap: 'preserve', // 使用默认的折行标准 always
      htmlWhitespaceSensitivity: 'css', // 根据显示样式决定 html 要不要折行
      vueIndentScriptAndStyle: false, //(默认值)对于 .vue 文件,不缩进 <script> 和 <style> 里的内容
      endOfLine: 'lf', // 换行符使用 lf 在Linux和macOS以及git存储库内部通用\n
      embeddedLanguageFormatting: 'auto' //(默认值)允许自动格式化内嵌的代码块,
    }
    
  • 根目录创建忽略:.prettierignore

    /dist/*
    .local
    .output.js
    /node_modules/**
        
    **/*.svg
    **/*.sh
        
    /public/*
    
  • settings.json 文件中添加如下配置代码
    请添加图片描述

    "editor.formatOnSave": true, // 每次保存的时候自动格式化
      "editor.formatOnPaste": true, // 自动格式化粘贴内容
      "editor.codeActionsOnSave": {
        // 保存时使用 ESLint 修复可修复错误
        "source.fixAll": true,
        "source.fixAll.eslint": true // 保存时使用 ESLint 修复可修复错误
        // "source.fixAll.stylelint": true
      },
      // 文件设置
      "files.eol": "\n", // 默认行尾字符。 git全局配置 git config --global core.autocrlf false
      // eslint 设置
      "eslint.alwaysShowStatus": true, // 总是显示 ESlint 状态栏项
      "eslint.probe": [
        // eslint 校验的语言类型
        "javascript",
        "javascriptreact",
        "typescript",
        "typescriptreact",
        "html",
        "vue",
        "markdown",
        "tsx"
      ],
    
3、集成editorconfig配置

EditorConfig 有助于为不同 IDE 编辑器上处理同一项目的多个开发人员维护一致的编码风格。

  • 安装插件

    EditorConfig for VS Code
    

    请添加图片描述

  • 在项目根目录创建 :.editorconfig

    # http://editorconfig.org
        
    root = true
        
    [*] # 表示所有文件适用
    charset = utf-8 # 设置文件字符集为 utf-8
    indent_style = space # 缩进风格(tab | space)
    indent_size = 2 # 缩进大小
    end_of_line = lf # 控制换行类型(lf | cr | crlf)
    trim_trailing_whitespace = true # 去除行首的任意空白字符
    insert_final_newline = true # 始终在文件末尾插入一个新行
        
    [*.md] # 表示仅 md 文件适用以下规则
    max_line_length = off
    trim_trailing_whitespace = false
    
4、git commit规范
Type作用
feat新增特性 (feature)
fix修复 Bug(bug fix)
docs修改文档 (documentation)
style代码格式修改(white-space, formatting, missing semi colons, etc)
refactor代码重构(refactor)
perf改善性能(A code change that improves performance)
test测试(when adding missing tests)
build变更项目构建或外部依赖(例如 scopes: webpack、gulp、npm 等)
ci更改持续集成软件的配置文件和 package 中的 scripts 命令,例如 scopes: Travis, Circle 等
chore变更构建流程或辅助工具(比如更改测试环境)
revert代码回退

三、项目配置

一、css预处理器及样式重置
1、css预处理器
  • scss安装(选其一)

    npm i sass-loader node-sass -S
    
    // 使用
    <style lang="scss" scoped></style>
    
  • less安装(选其一)

    npm i less less-loader
    
    // 使用
        <style lang="less" scoped></style>
    
2、样式重置
  • 1、安装 normalize.css

    npm i normalize.css
    
  • 2、引入

    // main.ts
    import 'normalize.css'
    
  • 3、reset.css

    html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,
    u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,caption {
      margin: 0;
      padding: 0;
      border: 0;
      outline: 0;
      font-size: 100%;
      vertical-align: baseline;
      background: transparent;
    }
    
    table,tbody,tfoot,thead,tr,th,td {
      margin: 0;
      padding: 0;
      outline: 0;
      font-size: 100%;
      vertical-align: baseline;
      background: transparent;
    }
    
    button,input,textarea {margin: 0;padding: 0;}
    
    /* form elements 表单元素 */
    body,button,input,select,textarea {
      font: normal 12px/1.5 '\5FAE\8F6F\96C5\9ED1', tahoma, arial;
    }
    
    /*设置的字体,行高*/
    h1,h2,h3,h4,h5,h6,th {font-size: 100%;font-weight: normal;}
    
    /*重置标题*/
    address,cite,dfn,var {font-style: normal;}
    
    /* 将斜体扶正 */
    code,kbd,pre,samp {
      font-family: 'courier new', courier, monospace;
    }
    
    /* 统一等宽字体 */
    small {font-size: 12px;}
    
    /* 小于 12px 的中文很难阅读,让 small 正常化 */
    ul,ol {list-style: none;}
    
    /* 重置列表元素 */
    button,input[type='submit'],input[type='button'] {
      cursor: pointer;
    }
    
    input[type='radio'],input[type='checkbox'],input[type='submit'],input[type='reset'] {
      vertical-align: middle;
      cursor: pointer;
      border: none;
    }
    
    /** 重置文本格式元素 **/
    a {text-decoration: none;}
    
    a:hover {text-decoration: underline;}
    
    a:focus {outline: 0;}
    
    sup {vertical-align: text-top;}
    
    /* 重置,减少对行高的影响 */
    sub {vertical-align: text-bottom;}
    
    /** 重置表单元素 **/
    legend {color: #000;}
    
    /* for ie6 */
    fieldset,img {border: 0;}
    
    /* img 搭车:让链接里的 img 无边框 */
    button,input,select,textarea {
      background: transparent;
      font-size: 100%;
      outline: 0;
    }
    
    /* 使得表单元素在 ie 下能继承字体大小 */
    
    /* 注:optgroup 无法扶正 */
    table {border-collapse: collapse; border-spacing: 0;}
    
    td,th {
      vertical-align: middle;
    }
    
    /** 重置表格元素 **/
    
    /* 重置 HTML5 元素 */
    article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section,summary,time,mark,audio,
    video {
      display: block;
      margin: 0;
      padding: 0;
    }
    
    /*回复标签重置*/
    blockquote,q {quotes: none;}
    
    blockquote:before,blockquote:after,q:before,q:after {
      content: '';
      display: none;
    }
    
  • common.css (一直完善中…)

    
    /* 字体颜色 */
    .clfff{color: #fff;}
    .cl00baad{color: #00baad;}
    .clff6262{color: #ff6262;}
    .clc5cedd{color: #c5cedd;}
    .cl909399{color: #909399;}
    .cl808080{color: #808080;}
    
    
    .ls2{letter-spacing: 2px;}
    .text-2{text-indent: 2rem;}
    /* 背景颜色 */
    .bgfff{background-color: #fff;}
    
    /* 字体大小 */
    .fs12 {font-size: 12px;}
    .fs16 {font-size: 16px;}
    .fs18 {font-size: 18px;}
    .fs20 {font-size: 20px;}
    .fs22 {font-size: 22px;}
    .fs24 {font-size: 24px;}
    
    /* 圆角边框 */
    .br6{border-radius: 6px;}
    .br8{border-radius: 8px;}
    .br10{border-radius: 10px;}
    
    /* 内边距 */
    .pd5{padding: 5px;}
    .pd10{padding: 10px;}
    .pd15{padding: 15px;}
    .pd20{padding: 20px;}
    .pd25{padding: 25px;}
    .pd30{padding: 30px;}
    .pd35{padding: 35px;}
    .pd40{padding: 40px;}
    .pd45{padding: 45px;}
    .pd50{padding: 50px;}
    
    .pdt5{padding-top: 5px;}
    .pdt10{padding-top: 10px;}
    .pdt15{padding-top: 15px;}
    .pdt20{padding-top: 20px;}
    .pdt25{padding-top: 25px;}
    .pdt30{padding-top: 30px;}
    .pdt35{padding-top: 35px;}
    .pdt40{padding-top: 40px;}
    .pdt45{padding-top: 45px;}
    .pdt50{padding-top: 50px;}
    
    .pdb5{padding-bottom: 5px;}
    .pdb10{padding-bottom: 10px;}
    .pdb15{padding-bottom: 15px;}
    .pdb20{padding-bottom: 20px;}
    .pdb25{padding-bottom: 25px;}
    .pdb30{padding-bottom: 30px;}
    .pdb35{padding-bottom: 35px;}
    .pdb40{padding-bottom: 40px;}
    .pdb45{padding-bottom: 45px;}
    .pdb50{padding-bottom: 50px;}
    
    .pdl5{padding-left: 5px;}
    .pdl10{padding-left: 10px;}
    .pdl15{padding-left: 15px;}
    .pdl20{padding-left: 20px;}
    .pdl25{padding-left: 25px;}
    .pdl30{padding-left: 30px;}
    .pdl35{padding-left: 35px;}
    .pdl40{padding-left: 40px;}
    .pdl45{padding-left: 45px;}
    .pdl50{padding-left: 50px;}
    
    .pdr5{padding-right: 5px;}
    .pdr10{padding-right: 10px;}
    .pdr15{padding-right: 15px;}
    .pdr20{padding-right: 20px;}
    .pdr25{padding-right: 25px;}
    .pdr30{padding-right: 30px;}
    .pdr35{padding-right: 35px;}
    .pdr40{padding-right: 40px;}
    .pdr45{padding-right: 45px;}
    .pdr50{padding-right: 50px;}
    
    /* 外边距 */
    .mg5{margin: 5px;}
    .mg10{margin: 10px;}
    .mg15{margin: 15px;}
    .mg20{margin: 20px;}
    .mg25{margin: 25px;}
    .mg30{margin: 30px;}
    .mg35{margin: 35px;}
    .mg40{margin: 40px;}
    .mg45{margin: 45px;}
    .mg50{margin: 50px;}
    
    .mgt5{margin-top: 5px;}
    .mgt10{margin-top: 10px;}
    .mgt15{margin-top: 15px;}
    .mgt20{margin-top: 20px;}
    .mgt25{margin-top: 25px;}
    .mgt30{margin-top: 30px;}
    .mgt35{margin-top: 35px;}
    .mgt40{margin-top: 40px;}
    .mgt45{margin-top: 45px;}
    .mgt50{margin-top: 50px;}
    
    .mgb5{margin-bottom: 5px;}
    .mgb10{margin-bottom: 10px;}
    .mgb15{margin-bottom: 15px;}
    .mgb20{margin-bottom: 20px;}
    .mgb25{margin-bottom: 25px;}
    .mgb30{margin-bottom: 30px;}
    .mgb35{margin-bottom: 35px;}
    .mgb40{margin-bottom: 40px;}
    .mgb45{margin-bottom: 45px;}
    .mgb50{margin-bottom: 50px;}
    
    .mgl5{margin-left: 5px;}
    .mgl10{margin-left: 10px;}
    .mgl15{margin-left: 15px;}
    .mgl20{margin-left: 20px;}
    .mgl25{margin-left: 25px;}
    .mgl30{margin-left: 30px;}
    .mgl35{margin-left: 35px;}
    .mgl40{margin-left: 40px;}
    .mgl45{margin-left: 45px;}
    .mgl50{margin-left: 50px;}
    
    .mgr5{margin-right: 5px;}
    .mgr10{margin-right: 10px;}
    .mgr15{margin-right: 15px;}
    .mgr20{margin-right: 20px;}
    .mgr25{margin-right: 25px;}
    .mgr30{margin-right: 30px;}
    .mgr35{margin-right: 35px;}
    .mgr40{margin-right: 40px;}
    .mgr45{margin-right: 45px;}
    .mgr50{margin-right: 50px;}
    
    /* 文字省略 u-line-1 u-line-2 u-line-3 u-line-4*/
    .u-line-2{
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }
    
    /* flex布局 */
    .u-flex{display: flex;}
    
    /* 垂直居中 */
    .ai-c{align-items: center;}
    /* 水平居中 */
    .jc-c{justify-content: center;}
    .jc-b{justify-content: space-between;}
    .jc-r{justify-content: flex-end;}
    
    /* 空间分布 */
    .flex-1{flex: 1;}
    .flex-2{flex: 2;}
    
    /* 字体大小 */
    .fw700{font-weight: 700;}
    
    /* 手型 */
    .cp{cursor: pointer;}
    
    /* 文字对齐 */
    .ac{text-align: center;}
    .ar{text-align: right;}
    .al{text-align: left;}
    
    /* 清除默认样式 */
    * {margin: 0; padding: 0;}
    html,body,#app {width: 100%;height: 100%;}
    
    
二、引入Element-Plus 官网
  • 安装Element-Plus

    // NPM
     npm install element-plus --save
    
    // Yarn
     yarn add element-plus
    
    // pnpm
     pnpm install element-plus
    
  • 全局引入

    // main.ts
    
    import ElementPlus from 'element-plus'
    import 'element-plus/dist/index.css'
    
    app.use(ElementPlus)
    
三、环境变量配置

设置.env中的内容信息 注意vue3+vite 必须使用VITE开头的配置信息 否则无法获取

  • 配置开发环境(npm run serve)

    // 1.在项目的根目录下创建一个文件
        .env.development
        
    // 2.在文件中添加我们要配置的变量:
        变量名结构: VITE_APP_XXX
        例如: VITE_APP_BASEURL = http://localhost:5000
        
    // 3.在要使用的位置获取:
        import.meta.env.VITE_APP_BASEURL
    
  • 配置生产环境(npm run build)

    // 1.在项目的根目录下创建一个文件
        .env.production
        
    // 2.在文件中添加我们要配置的变量:
        变量名结构: VITE_APP_XXX
        例如: VITE_APP_BASEURL = http://152.136.185.210:5000
        
    // 3.在要使用的位置获取:
        import.meta.env.VITE_APP_BASEURL
    
四、axios集成
1、安装axios
npm i axios
2、封装请求错误代码提示: /src/utils/error-code-type.ts
export const errorCodeType = function (code: number, message: string): string {
  let errMessage = '未知错误'
  switch (code) {
    case 400:
      errMessage = '错误的请求'
      break
    case 401:
      errMessage = '未授权,请重新登录'
      break
    case 403:
      errMessage = '拒绝访问'
      break
    case 404:
      errMessage = '请求错误,未找到该资源'
      break
    case 405:
      errMessage = '请求方法未允许'
      break
    case 408:
      errMessage = '请求超时'
      break
    case 500:
      errMessage = '服务器端出错'
      break
    case 501:
      errMessage = '网络未实现'
      break
    case 502:
      errMessage = '网络错误'
      break
    case 503:
      errMessage = '服务不可用'
      break
    case 504:
      errMessage = '网络超时'
      break
    case 505:
      errMessage = 'http版本不支持该请求'
      break
    default:
      errMessage = message
  }
  return errMessage
}
3、封装:/src/utils/request.ts
import axios from 'axios'
import { errorCodeType } from './error-code-type'
import { ElMessage } from 'element-plus'

/** 创建axios实例 */
const service = axios.create({
  timeout: 100000, // 超时时间
  baseURL: import.meta.env.VITE_APP_BASEURL,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

//2. 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 是否需要设置 token放在请求头
    // config.headers['Authorization'] = 'Bearer ' + getToken()
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

//3. 响应拦截器
service.interceptors.response.use(
  (response) => {
    const code = response.data['code']
    const message = response.data['message']
    // 获取错误信息
    const msg = errorCodeType(code, message)
    if (code === 200) {
      return Promise.resolve(response.data)
    } else {
      ElMessage.error(msg)
      return Promise.reject(response.data)
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service

4、封装请求接口
import request from '@/utils/request'
//请求示例
//get
export const mokeGet = (data) => {
    return axios({
        url: "/api/xxxx",
        method: "get",
        data,
    })
}

//post
export const mokePost = (data) => {
    return axios({
        url: "/api/xxxx",
        method: "post",
        data,
    })
}

5、vue中使用
import { mokePost } from "@/api";
import {onMounted} from "vue"
export default {
  setup() {
     onMounted(() => {
      mokePost().then(res=>{
        console.log(res)
      })
    })
    return {};
  },
};
五、封装本地存储(localStorage)
// 操作本地存储(localStorage)

const local = {
  getToken(key) {
    if (!key) return
    return window.localStorage.getItem(key)
  },
  get(key) {
    if (!key) return
    return JSON.parse(window.localStorage.getItem(key))
  },
  set(key, value) {
    if (!key) return
    if (typeof value !== 'string') {
      value = JSON.stringify(value)
    }
    window.localStorage.setItem(key, value)
  },
  clear() {
    window.localStorage.clear()
  },
  remove(key) {
    if (!key) return
    window.localStorage.removeItem(key)
  }
}
export default local
六、工具函数封装
// 防抖
export const debounce = (() => {
  let timer = null
  return (callback, wait) => {
    clearTimeout(timer)
    timer = setTimeout(callback, wait)
  }
})()

// 验证密码 - 请输入6 ~ 14位,数字/字母/下划线/-
export const isPassword = (val) => {
  return /^[a-zA-Z0-9_-]{6,20}$/.test(val)
}

// 验证用户名 - 姓名不能有数字
export const isName = (val) => {
  return /^[^\d]*$/.test(val)
}

// 验证手机号 - 请输入正确的手机号
export const isPhone = (val) => {
  return /^1(3|4|5|7|8|9)\d{9}$/.test(val)
}

// 验证账号 - 账号不能输入汉字
export const isAccount = (val) => {
  return /^[^\u4e00-\u9fa5]+$/.test(val)
}
五、扩展
1、本地打开vue3+vite+ts项目打包的dist文件夹下index.html
import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

// https://vitejs.dev/config/
export default defineConfig({
  //本地打开dist文件夹下index.html
  base: './',
  plugins: [vue(), vueJsx()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})
2、vite项目中配置路径别名@
  • vite.config.ts中添加如下代码

    import { resolve } from "path"
     
    export default defineConfig({
      ......
     
      resolve: {
        alias: {
          "@": resolve(__dirname, "./src"),
        },
      },
    })
    
  • 在tsconfig.json中的compilerOptions里面添加代码:

    "compilerOptions"{
        ......
     
        "baseUrl": ".",
        "paths": {
           "@/*": ["src/*"]
        }
    }
    
    //重启项目即可
    
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Vue3 + TypeScript + Vite + Element Plus + Router + Axios搭建前端项目框架的步骤: 1. 首先,确保你已经安装了Node.js和npm。你可以在命令行中运行以下命令来检查它们的版本: ```shell node -v npm -v ``` 2. 创建一个新的项目文件夹,并在该文件夹中打开命令行。 3. 在命令行中运行以下命令来初始化一个新的Vite项目: ```shell npm init vite ``` 在初始化过程中,你需要选择Vue作为模板,选择TypeScript作为语言,并填写项目名称。 4. 进入项目文件夹,并安装所需的依赖: ```shell cd your-project-name npm install ``` 5. 安装Vue Router、Vuex和Axios: ```shell npm install vue-router@next vuex@next axios ``` 6. 在项目文件夹中创建一个新的文件夹,用于存放页面组件和路由配置文件。 7. 在src文件夹中创建一个新的文件夹,用于存放页面组件。 8. 在src文件夹中创建一个新的文件夹,用于存放路由配置文件。 9. 在src/router文件夹中创建一个新的文件,命名为index.ts,并在其中编写路由配置: ```typescript import { createRouter, createWebHistory } from 'vue-router'; import Home from '../views/Home.vue'; const routes = [ { path: '/', name: 'Home', component: Home, }, // 添加其他页面的路由配置 ]; const router = createRouter({ history: createWebHistory(), routes, }); export default router; ``` 10. 在src/main.ts文件中导入并使用Vue Router: ```typescript import { createApp } from 'vue'; import App from './App.vue'; import router from './router'; createApp(App).use(router).mount('#app'); ``` 11. 在src/views文件夹中创建一个新的文件,命名为Home.vue,并在其中编写一个简单的页面组件: ```vue <template> <div> <h1>Welcome to Home Page</h1> </div> </template> <script> export default { name: 'Home', }; </script> ``` 12.src/App.vue文件中添加一个路由出口,用于显示组件: ```vue <template> <div id="app"> <router-view></router-view> </div> </template> <script> export default { name: 'App', }; </script> ``` 13. 在src/main.ts文件中导入并使用Element Plus: ```typescript import { createApp } from 'vue'; import App from './App.vue'; import router from './router'; import ElementPlus from 'element-plus'; import 'element-plus/lib/theme-chalk/index.css'; createApp(App).use(router).use(ElementPlus).mount('#app'); ``` 14. 运行以下命令来启动开发服务器: ```shell npm run dev ``` 15. 打开浏览器,并访问http://localhost:3000,你将看到一个简单的页面,其中包含"Welcome to Home Page"的文本。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值