uniapp-vue3-vite 搭建小步伐、H5 项目模板

[复制链接]
发表于 2026-2-21 18:09:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×

   作者GitHub:https://github.com/gitboyzcf 有爱好可关注!!!
  特色



  • ⚡️uni-app, Vue 3, Vite, pnpm
  • 📦 组件自动化引入
  • 🍍 利用 Pinia 的状态管理
  • 🎨 UnoCSS - 高性能且极具机动性的即时原子化 CSS 引擎
  • 😃 各种图标集为你所用
  • 🔥 利用 新的 <script setup> 语法
  • 📥 API 自动加载 - 直接利用 Composition API 无需引入
  • 🌍 API 接纳模块化自动导入方式 根据demo.js文件设置接口,以API_xxx_method的方式定名,在哀求时无需导入 直接利用useRequest()函数返回参数以解构的方式获取,拿到即为写入的接口
准备

Vue3/Vite版要求 node 版本^14.18.0 || >=16.0.0
拉取默认UniApp模板

点击下载 默认模板,大概通过下面下令行拉取
  1. npx degit dcloudio/uni-preset-vue#vite my-vue3-project
复制代码
得到下面貌次结构👇

安装依赖

我这里利用pnpm ,可以利用如npm、yarn、…
  1. pnpm install
复制代码
如有报下面错误👇
   This modules directory was created using the following registries configuration:{“default”:“https://registry.npmjs.org/”}. The current configuration is {“default”:“https://registry.npm.taobao.org/”}. To recreate the modules directory using the new settings, run “pnpm install
-g”.
  办理方案 下载源切换
  1. pnpm config set registry https://registry.npmjs.org
复制代码
启动项目测试

实行该下令 会将此项目编译成微信小步伐项目,该下令会连续监听修改并举行热更新
  1. pnpm dev:mp-weixin
复制代码
实行后会出现 dist\dev\mp-weixin文件夹结构

将此目次下的mp-weixin用微信开辟者工具举行打开
如未安装点击下面链接下载安装即可👇
https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
结果


设置自动化导入

安装依赖

  1. pnpm i unplugin-auto-import -D
复制代码
在vite.config.js中设置


  1. import AutoImport from 'unplugin-auto-import/vite'
  2. AutoImport({
  3. imports: ["vue", "uni-app", "pinia"],
  4. dts: true,
  5. })
复制代码
设置完后 重新实行pnpm dev:mp-weixin
此时会天生auto-imports.d.ts文件
此时在pages/index/index.vue中不消引入直接可以利用vue的api
  1. <script setup>
  2. const title = ref('Hello World!')
  3. </script>
复制代码
引入 prerttier + eslint + stylelint

安装干系依赖包👇
  1. pnpm add -D eslint @babel/eslint-parser eslint-config-airbnb-base eslint-config-prettier eslint-plugin-import eslint-plugin-prettier eslint-plugin-vue vue-global-api stylelint stylelint-scss stylelint-config-standard-scss stylelint-config-prettier
复制代码
.editorconfig

  1. # .editorconfig 文件
  2. root = true
  3. [*] # 表示所有文件适用
  4. charset = utf-8 # 设置文件字符集为 utf-8
  5. indent_style = space # 缩进风格(tab | space)
  6. indent_size = 2 # 缩进大小
  7. end_of_line = lf # 控制换行类型(lf | cr | crlf)
  8. trim_trailing_whitespace = true # 去除行首的任意空白字符
  9. insert_final_newline = true # 始终在文件末尾插入一个新行
  10. [*.md] # 表示仅 md 文件适用以下规则
  11. max_line_length = off # 关闭最大行长度限制
  12. trim_trailing_whitespace = false # 关闭末尾空格修剪
复制代码
.prettierrc.cjs

  1. module.exports = {
  2.   // 一行的字符数,如果超过会进行换行,默认为80,官方建议设100-120其中一个数
  3.   printWidth: 100,
  4.   // 一个tab代表几个空格数,默认就是2
  5.   tabWidth: 2,
  6.   // 启用tab取代空格符缩进,默认为false
  7.   useTabs: false,
  8.   // 行尾是否使用分号,默认为true(添加理由:更加容易复制添加数据,不用去管理尾行)
  9.   semi: false,
  10.   vueIndentScriptAndStyle: true,
  11.   // 字符串是否使用单引号,默认为false,即使用双引号,建议设true,即单引号
  12.   singleQuote: true,
  13.   // 给对象里的属性名是否要加上引号,默认为as-needed,即根据需要决定,如果不加引号会报错则加,否则不加
  14.   quoteProps: 'as-needed',
  15.   // 是否使用尾逗号,有三个可选值"<none|es5|all>"
  16.   trailingComma: 'none',
  17.   // 在jsx里是否使用单引号,你看着办
  18.   jsxSingleQuote: true,
  19.   // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
  20.   bracketSpacing: true,
  21.   proseWrap: 'never',
  22.   htmlWhitespaceSensitivity: 'strict',
  23.   endOfLine: 'auto',
  24. }
复制代码
.eslintrc.cjs

  1. // .eslintrc.cjs 文件
  2. module.exports = {
  3.   env: {
  4.     browser: true,
  5.     es2021: true,
  6.     node: true,
  7.   },
  8.   extends: [
  9.     'eslint:recommended',
  10.     'plugin:vue/vue3-essential',
  11.     // eslint-plugin-import 插件, @see https://www.npmjs.com/package/eslint-plugin-import
  12.     'plugin:import/recommended',
  13.     // eslint-config-airbnb-base 插件, tips: 本插件也可以替换成 eslint-config-standard
  14.     'airbnb-base',
  15.     // 1. 接入 prettier 的规则
  16.     'prettier',
  17.     'plugin:prettier/recommended',
  18.     'vue-global-api',
  19.   ],
  20.   overrides: [
  21.     {
  22.       env: {
  23.         node: true,
  24.       },
  25.       files: ['.eslintrc.{js}'],
  26.       parserOptions: {
  27.         sourceType: 'script',
  28.       },
  29.     },
  30.   ],
  31.   parserOptions: {
  32.     ecmaVersion: 'latest',
  33.     parser: '@babel/eslint-parser',
  34.     sourceType: 'module',
  35.   },
  36.   plugins: [
  37.     '@babel/eslint-parser',
  38.     'vue',
  39.     // 2. 加入 prettier 的 eslint 插件
  40.     'prettier',
  41.     // eslint-import-resolver-typescript 插件,@see https://www.npmjs.com/package/eslint-import-resolver-typescript
  42.     'import',
  43.   ],
  44.   rules: {
  45.     // 3. 注意要加上这一句,开启 prettier 自动修复的功能
  46.     'prettier/prettier': 'error',
  47.     // turn on errors for missing imports
  48.     'import/no-unresolved': 'off',
  49.     // 对后缀的检测,否则 import 一个ts文件也会报错,需要手动添加'.ts', 增加了下面的配置后就不用了
  50.     'import/extensions': [
  51.       'error',
  52.       'ignorePackages',
  53.       { js: 'never', jsx: 'never', ts: 'never', tsx: 'never' },
  54.     ],
  55.     // 只允许1个默认导出,关闭,否则不能随意export xxx
  56.     'import/prefer-default-export': ['off'],
  57.     'no-console': ['off'],
  58.     // 'no-unused-vars': ['off'],
  59.     // '@typescript-eslint/no-unused-vars': ['off'],
  60.     // 解决vite.config.ts报错问题
  61.     'import/no-extraneous-dependencies': 'off',
  62.     'no-plusplus': 'off',
  63.     'no-shadow': 'off',
  64.     'vue/multi-word-component-names': 'off',
  65.     '@typescript-eslint/no-explicit-any': 'off',
  66.   },
  67.   // eslint-import-resolver-typescript 插件,@see https://www.npmjs.com/package/eslint-import-resolver-typescript
  68.   settings: {
  69.     'import/parsers': {
  70.       '@typescript-eslint/parser': ['.ts', '.tsx'],
  71.     },
  72.     'import/resolver': {
  73.       typescript: {},
  74.     },
  75.   },
  76.   globals: {
  77.     uni: true,
  78.     UniApp: true,
  79.     wx: true,
  80.     WechatMiniprogram: true,
  81.     getCurrentPages: true,
  82.     UniHelper: true,
  83.     Page: true,
  84.     App: true,
  85.   },
  86. }
复制代码
.stylelintrc.cjs

  1. // .stylelintrc.cjs 文件
  2. module.exports = {
  3.   root: true,
  4.   extends: [
  5.     'stylelint-config-standard',
  6.     'stylelint-config-standard-scss', // tips: 本插件也可以替换成 stylelint-config-recommended-scss
  7.     'stylelint-config-recommended-vue/scss',
  8.     'stylelint-config-html/vue',
  9.     'stylelint-config-recess-order',
  10.   ],
  11.   overrides: [
  12.     // 扫描 .vue/html 文件中的<style>标签内的样式
  13.     {
  14.       files: ['**/*.{vue,html}'],
  15.       customSyntax: 'postcss-html',
  16.     },
  17.     {
  18.       files: ['**/*.{css,scss}'],
  19.       customSyntax: 'postcss-scss',
  20.     },
  21.   ],
  22.   // 自定义规则
  23.   rules: {
  24.     // 允许 global 、export 、v-deep等伪类
  25.     'selector-pseudo-class-no-unknown': [
  26.       true,
  27.       {
  28.         ignorePseudoClasses: ['global', 'export', 'v-deep', 'deep'],
  29.       },
  30.     ],
  31.     'unit-no-unknown': [
  32.       true,
  33.       {
  34.         ignoreUnits: ['rpx'],
  35.       },
  36.     ],
  37.     'selector-type-no-unknown': [
  38.       true,
  39.       {
  40.         ignoreTypes: ['page'],
  41.       },
  42.     ],
  43.     'comment-empty-line-before': 'never',
  44.   },
  45. }
复制代码
引入 husky + lint-staged + commitlint

   分析
husky 用于git提交的钩子
lint-staged 一个在 git 暂存文件上(也就是被git add后的文件)运行已设置的格式工具;好比eslint、stylelintrc、…
commitlint 查抄您的提交消息是否符合 通例提交格式 (Conventional commit format)
精确的提交格式:(): ,type 和 subject 默认必填

  安装干系依赖包👇
  1. pnpm i -D husky@6 lint-staged commitlint @commitlint/cli @commitlint/config-conventional
复制代码
实行 npx husky install
而且在 package.json的scripts内里增长 "prepare": "husky install",(其他人安装后会自动实行) 根目次会天生 .hushy 文件夹。
package.josn 增长如下属性👇:
  1. ...
  2. "scripts": {
  3.         ...
  4.         "prepare": "husky install",
  5. },
  6. "lint-staged": {
  7.   "**/*.{html,vue,ts,cjs,json,md}": [
  8.     "prettier --write"
  9.   ],
  10.   "**/*.{vue,js,ts,jsx,tsx}": [
  11.     "eslint --fix"
  12.   ],
  13.   "**/*.{vue,css,scss,html}": [
  14.     "stylelint --fix"
  15.   ]
  16. }
复制代码
根目次新增 .commitlintrc.cjs,内容如下👇
  1. module.exports = {
  2.   extends: ['@commitlint/config-conventional'],
  3.   rules: {
  4.     'type-enum': [
  5.       2,
  6.       'always',
  7.       [
  8.         'feat',
  9.         'fix',
  10.         'perf',
  11.         'style',
  12.         'docs',
  13.         'test',
  14.         'refactor',
  15.         'build',
  16.         'ci',
  17.         'init',
  18.         'chore',
  19.         'revert',
  20.         'wip',
  21.         'workflow',
  22.         'types',
  23.         'release',
  24.       ],
  25.     ],
  26.     'subject-case': [0],
  27.   },
  28. }
复制代码
通过下面下令在钩子文件中添加内容👇
  1. npx husky add .husky/pre-commit "npx --no-install -- lint-staged"
  2. npx husky add .husky/commit-msg "npx --no-install commitlint --edit $1"
复制代码
Commitizen & cz-git

   分析
commitizen 基于Node.js的 git commit 下令行工具,辅助天生尺度化规范化的 commit message
cz-customizable 尺度输特别式的 commitizen 适配器
  安装依赖包👇
  1. pnpm add -D commitizen cz-customizable
复制代码
修改 package.json指定利用的适配器
  1. ...
  2. "scripts": {
  3.         ...
  4.         "cz": "git-cz"
  5. },
  6. "config": {
  7.     "commitizen": {
  8.       "path": "node_modules/cz-customizable"
  9.     }
  10.   }
复制代码
更改提示消息模板 .cz-config.js

.cz-config.js
  1. module.exports = {
  2.   types: [
  3.     { value: 'feat', name: '✨ feat:     新功能' },
  4.     { value: 'fix', name: '🐛 fix:      修复' },
  5.     { value: 'init', name: '🎉 Init:     初始化' },
  6.     { value: 'docs', name: '📝 docs:     文档变更' },
  7.     { value: 'style', name: '💄 style:    代码格式(不影响代码运行的变动)' },
  8.     {
  9.       value: 'refactor',
  10.       name: '♻️  refactor: 重构(既不是增加feature,也不是修复bug)',
  11.     },
  12.     { value: 'perf', name: '⚡️ perf:     性能优化' },
  13.     { value: 'test', name: '✅ test:     增加测试' },
  14.     { value: 'revert', name: '⏪️ Revert:   回退' },
  15.     { value: 'build', name: '🚀‍ build:    构建过程或辅助工具的变动' },
  16.     { value: 'ci', name: '👷 ci:       CI 配置' },
  17.   ],
  18.   // 消息步骤
  19.   messages: {
  20.     type: '请选择提交类型:',
  21.     subject: '请简要描述提交(必填):',
  22.     customScope: '请输入修改范围(可选):',
  23.     body: '请输入详细描述(可选):',
  24.     breaking: '列出任何BREAKING CHANGES(可选)',
  25.     footer: '请输入要关闭的issue(可选):',
  26.     confirmCommit: '确认使用以上信息提交吗?',
  27.   },
  28.   allowBreakingChanges: ['feat', 'fix'],
  29.   skipQuestions: ['customScope'],
  30.   subjectLimit: 72,
  31. }
复制代码
检测

在下令行中输入👇
  1. git add .
  2. pnpm cz
复制代码
然后会出现本次提交选项

选择本次提交的范例,按要求写入然后回车即可
设置UnoCss

安装依赖👇
  1. pnpm add -D unocss @unocss/preset-uno unocss-applet @unocss/preset-legacy-compat
  2. pnpm add @uni-helper/unocss-preset-uni
复制代码
然后设置 unocss.config.js
  1. // uno.config.js
  2. import {
  3.   Preset,
  4.   defineConfig,
  5.   presetAttributify,
  6.   presetIcons,
  7.   transformerDirectives,
  8.   transformerVariantGroup,
  9. } from 'unocss'
  10. import {
  11.   presetApplet,
  12.   presetRemRpx,
  13.   transformerApplet,
  14.   transformerAttributify,
  15. } from 'unocss-applet'
  16. import { presetUni } from '@uni-helper/unocss-preset-uni'
  17. // @see https://unocss.dev/presets/legacy-compat
  18. import presetLegacyCompat from '@unocss/preset-legacy-compat'
  19. const isH5 = process.env?.UNI_PLATFORM === 'h5'
  20. const isMp = process.env?.UNI_PLATFORM?.startsWith('mp') ?? false
  21. const presets = []
  22. if (!isMp) {
  23.   /**
  24.    * you can add `presetAttributify()` here to enable unocss attributify mode prompt
  25.    * although preset is not working for applet, but will generate useless css
  26.    * 为了不生产无用的css,要过滤掉 applet
  27.    */
  28.   // 支持css class属性化,eg: `<button bg="blue-400 hover:blue-500 dark:blue-500 dark:hover:blue-600" text="sm white">attributify Button</button>`
  29.   presets.push(presetAttributify())
  30. }
  31. if (!isH5) {
  32.   presets.push(presetRemRpx())
  33. }
  34. export default defineConfig({
  35.   presets: [
  36.     presetApplet({ enable: !isH5 }),
  37.     ...presets,
  38.     // 支持图标,需要搭配图标库,eg: @iconify-json/carbon, 使用 `<button class="i-carbon-sun dark:i-carbon-moon" />`
  39.     presetIcons({
  40.       scale: 1.2,
  41.       warn: true,
  42.       extraProperties: {
  43.         display: 'inline-block',
  44.         'vertical-align': 'middle',
  45.       },
  46.     }),
  47.     // 将颜色函数 (rgb()和hsl()) 从空格分隔转换为逗号分隔,更好的兼容性app端,example:
  48.     // `rgb(255 0 0)` -> `rgb(255, 0, 0)`
  49.     // `rgba(255 0 0 / 0.5)` -> `rgba(255, 0, 0, 0.5)`
  50.     presetLegacyCompat({
  51.       commaStyleColorFunction: true,
  52.     }),
  53.   ],
  54.   /**
  55.    * 自定义快捷语句
  56.    * @see https://github.com/unocss/unocss#shortcuts
  57.    */
  58.   shortcuts: [['center', 'flex justify-center items-center']],
  59.   transformers: [
  60.     // 启用 @apply 功能
  61.     transformerDirectives(),
  62.     // 启用 () 分组功能
  63.     // 支持css class组合,eg: `<div class="hover:(bg-gray-400 font-medium) font-(light mono)">测试 unocss</div>`
  64.     transformerVariantGroup(),
  65.     // Don't change the following order
  66.     transformerAttributify({
  67.       // 解决与第三方框架样式冲突问题
  68.       prefixedOnly: true,
  69.       prefix: 'fg',
  70.     }),
  71.     transformerApplet(),
  72.   ],
  73.   rules: [
  74.     [
  75.       'p-safe',
  76.       {
  77.         padding:
  78.           'env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)',
  79.       },
  80.     ],
  81.     ['pt-safe', { 'padding-top': 'env(safe-area-inset-top)' }],
  82.     ['pb-safe', { 'padding-bottom': 'env(safe-area-inset-bottom)' }],
  83.   ],
  84. })
复制代码
在src/main.js增长 import 'virtual:uno.css'
在 vite.config.js文件写入:
  1. import UnoCSS from 'unocss/vite'
  2. // 其他配置省略
  3. plugins: [UnoCSS()],
复制代码
检测

  1. <view class="text-area b-1px b-solid b-color-red">
  2.   <text class="title mt-4">{{ title }}</text>
  3. </view>
复制代码
结果👇

设置pinia 添加长期化

起首安装依赖包:
  1. pnpm add pinia pinia-plugin-persistedstate -S
复制代码
然后写入文件:
  1. // src/store/count.js
  2. import { piniaStore } from '@/store'
  3. export const useCountStore = defineStore('count', {
  4.   state: () => {
  5.     return {
  6.       count: 0
  7.     }
  8.   },
  9.   actions: {
  10.     increment() {
  11.       this.count++
  12.     }
  13.   },
  14.   persist: true // 配置持久化
  15. })
  16. export function useOutsideCountStore(){
  17.   return useCountStore(piniaStore)
  18. }
复制代码
注意下面👇这个文件对长期化的处理惩罚,否则非h5情况不能精确长期化
  1. // src/store/index.js
  2. import { createPinia } from 'pinia'
  3. import { createPersistedState } from 'pinia-plugin-persistedstate' // 数据持久化
  4. const store = createPinia()
  5. store.use(
  6.   createPersistedState({
  7.     storage: {
  8.       getItem: uni.getStorageSync,
  9.       setItem: uni.setStorageSync,
  10.     },
  11.   }),
  12. )
  13. export function setupStore(app) {
  14.   app.use(piniaStore)
  15. }
复制代码
  1. // src/main.js
  2. import { createSSRApp } from 'vue'
  3. import App from './App.vue'
  4. import { setupStore } from './store'
  5. import 'virtual:uno.css'
  6. export function createApp() {
  7.   const app = createSSRApp(App)
  8.   setupStore(app)
  9.   return {
  10.     app
  11.   }
  12. }
复制代码
如有报下面错误👇
vue pinia版本辩论题目
   Not able to use pinia: No matching export in “node_modules/pinia/node_modules/vue-demi/lib/index.mjs” for import “hasInjectionContext”
  办理方案
将vue3 和pinia更换成下面版本重新下载对应npm包
“pinia”: “2.0.32”,
“vue”: “3.2.47”,
复制代码
详细请看:https://github.com/vuejs/pinia/issues/2210
检测

  1. <view>
  2. <button type="primary" @click="useCountStore.count++">点击 {{ count }}</button>
  3. </view>
  4. <script setup>
  5.   import { useOutsideCountStore } from '@/store/count'
  6.   const useCountStore = useOutsideCountStore()
  7.   const count = computed(() => useCountStore.count)
  8. </script>
复制代码

Axios接入设置

安装干系依赖包👇
  1. pnpm add @uni-helper/axios-adapter axios
复制代码
以下步调创建对应文件粘贴代码即可

  • src》api》index.js
    1. /**
    2. * 模块化方式处理 默认处理 modules文件夹下的所有js文件 内容以export default导出的文件
    3. * @param { 模块内容集合 } moduleContext
    4. * @returns modules集合
    5. */
    6. const modulesHandle = (moduleContext = {}) => {
    7.   if (!Object.keys(moduleContext).length) return
    8.   const modules = {}
    9.   Object.keys(moduleContext).forEach((v) => {
    10.     for (let key in moduleContext[v].default) {
    11.       modules[key] = moduleContext[v].default[key]
    12.     }
    13.   })
    14.   return modules
    15. }
    16. const apis = modulesHandle(import.meta.glob('./modules/**/*.js', { eager: true }))
    17. export const useRequest = () => apis
    复制代码
  • src》api》utils.js
    1. // 请求状态错误
    2. export const httpLogError = (error, msg) => {
    3.   error.message = msg
    4.   uni.showToast({
    5.     title: msg,
    6.     icon: 'error',
    7.     duration: 2000
    8.   })
    9. }
    10. // api请求错误
    11. export const requestError = (response) => {
    12.   return new Promise((_, reject) => {
    13.     const { data } = response
    14.     const msg = `api请求出错 ${response.config.url}:${data.message}`
    15.     uni.showToast({
    16.       title: msg,
    17.       icon: 'error',
    18.       duration: 2000
    19.     })
    20.     reject(data)
    21.   })
    22. }
    23. // 登录失效
    24. export const throttleToLogin = () => {
    25.   // uni.navigateTo({ url: '/pages/login/login' })
    26. }
    复制代码
  • src》api》service.js
    1. import axios from 'axios'
    2. import { createUniAppAxiosAdapter } from '@uni-helper/axios-adapter'
    3. import { httpLogError, requestError, throttleToLogin } from './utils'
    4. export function createService() {
    5.   const request = axios.create({ adapter: createUniAppAxiosAdapter() })
    6.   request.interceptors.request.use(
    7.     (request) => {
    8.       return request
    9.     },
    10.     (err) => {
    11.       return Promise.reject(err)
    12.     }
    13.   )
    14.   request.interceptors.response.use(
    15.     (response) => {
    16.       const dataAxios = response.data
    17.       // 这个状态码是和后端约定的
    18.       const { code, data } = dataAxios
    19.       console.log(dataAxios);
    20.       // 根据 code 进行判断
    21.       if (code === undefined) {
    22.         return dataAxios
    23.       } else {
    24.         // 目前和公司后端口头约定是字符串,以防万一强制转字符串
    25.         switch (`${code}`) {
    26.           // code === 200 | 2 代表没有错误
    27.           case '200':
    28.             return data
    29.           // code === 400001004 代表token 过期打回登录页
    30.           case '400001004':
    31.             throttleToLogin()
    32.             break
    33.           case '400':
    34.             // 不是正确的 code
    35.             return requestError(response)
    36.           case '401':
    37.             // 错误登录
    38.             return throttleToLogin()
    39.           default:
    40.             // 不是正确的 code
    41.             return requestError(response)
    42.         }
    43.       }
    44.     },
    45.     (error) => {
    46.       console.log(error);
    47.       const status = error.response?.status
    48.       switch (status) {
    49.         // TODO 再考虑下怎么判断是跨域问题
    50.         case undefined:
    51.         case null:
    52.           httpLogError(error, '网路错误或跨域')
    53.           break
    54.         case 400:
    55.           httpLogError(error, '请求错误')
    56.           break
    57.         case 401:
    58.           httpLogError(error, '未授权,请登录')
    59.           break
    60.         case 403:
    61.           httpLogError(error, '拒绝访问')
    62.           break
    63.         case 404:
    64.           httpLogError(error, `请求地址出错: ${error.response.config.url}`)
    65.           break
    66.         case 408:
    67.           httpLogError(error, '请求超时')
    68.           break
    69.         case 500:
    70.           httpLogError(error, '服务器内部错误')
    71.           break
    72.         case 501:
    73.           httpLogError(error, '服务未实现')
    74.           break
    75.         case 502:
    76.           httpLogError(error, '网关错误')
    77.           break
    78.         case 503:
    79.           httpLogError(error, '服务不可用')
    80.           break
    81.         case 504:
    82.           httpLogError(error, '网关超时')
    83.           break
    84.         case 505:
    85.           httpLogError(error, 'HTTP版本不受支持')
    86.           break
    87.         default:
    88.           httpLogError(error, '请求错误')
    89.           break
    90.       }
    91.       return Promise.reject(error)
    92.     }
    93.   )
    94.   return request
    95. }
    96. export const service = createService()
    复制代码
  • src》api》request.js
    1. import { service } from './service'
    2. function createRequest(service) {
    3.   function request(config) {
    4.           // config 自定义配置
    5.     // axios默认配置
    6.     const configDefault = {
    7.       baseURL: import.meta.env.VITE_APP_API_BASEURL, // 所有通过此配置的基础地址 在.env文件配置
    8.       timeout: 15000, // 请求超时时间
    9.       responseType: 'json', // 响应类型
    10.       headers: {
    11.         // 请求头配置...
    12.       }
    13.     }
    14.     const requestConfig = Object.assign(configDefault, config)
    15.     return service(requestConfig)
    16.   }
    17.   return request
    18. }
    19. export const request = createRequest(service)
    复制代码
  • src》modules》demo.js
    1. /**
    2. * 命名=》API_xxx_methodName
    3. */
    4. import { request } from '@/api/request.js'
    5. export default {
    6.   API_DEMO_POST(data = {}) {
    7.     return request({
    8.       url: 'demo/mock',
    9.       method: 'post',
    10.       data
    11.     })
    12.   },
    13.   API_DEMO_GET(params = {}) {
    14.     return request({
    15.       url: '/demo/get',
    16.       method: 'get',
    17.       params
    18.     })
    19.   }
    20. }
    复制代码
在vite.config.js中设置自动化导入

在原有的设置中添加
  1. import { defineConfig } from 'vite'
  2. import AutoImport from 'unplugin-auto-import/vite'
  3. // ...
  4. // https://vitejs.dev/config/
  5. export default defineConfig({
  6.   plugins: [
  7.           //...
  8.     AutoImport({
  9.       imports: [
  10.        //...
  11.         {
  12.           '@/api': ['useRequest']
  13.         }
  14.       ],
  15.       //...
  16.     }),
  17.     //...
  18.   ],
  19.   //...
  20. })
复制代码
检测

  1. <template>
  2.   <view class="content">
  3.     <view><button type="primary" @click="getList">点击请求数据</button></view>
  4.   </view>
  5.   <view class="p-2">
  6.     <view
  7.       class="my-15rpx b-b-solid b-b-1rpx b-b-color-[#cccccc]"
  8.       v-for="item in list"
  9.       :key="item.id"
  10.     >
  11.       <text class="text-18rpx font-bold">{{ item.title }}</text>
  12.       <view class="mt-4 text-12rpx color-[#9999]">{{ item.body }}</view>
  13.     </view>
  14.   </view>
  15. </template>
  16. <script setup>
  17.   const { API_DEMO_GET } = useRequest()
  18.   const list = ref([])
  19.   
  20.   const getList = () => {
  21.     uni.showLoading({
  22.       title: '加载中...'
  23.     })
  24.     API_DEMO_GET()
  25.       .then((res) => {
  26.         console.log(res)
  27.         list.value = res
  28.         uni.hideLoading()
  29.       })
  30.       .catch(() => {
  31.         uni.hideLoading()
  32.       })
  33.   }
  34. </script>
复制代码

图标库


  • 前去图标库查找干系图标iconify.design
  • 安装图标所在的图标库
    1. # 格式:pnpm add @iconify-json/[the-collection-you-want] -D
    2. # 例如
    3. pnpm add @iconify-json/ep -D
    复制代码
    安装完后可以利用当前库下的全部图标
    https://icon-sets.iconify.design/ep/
  • 项目中利用
    利用unocss的方式https://iconify.design/docs/usage/css/unocss/#icons-with-unocss
    1. <text class="i-ep-apple w-40rpx h-40rpx color-red"></text>
    复制代码
UI 方案

自利用用干系ui接入项目
uni-ui
https://www.uvui.cn/
https://uviewui.com/
当前文章模板接纳 nutui-uniapp京东风格的轻量级移动端组件库
接入步调请自行检察对应文档即可👉 https://nutui-uniapp.pages.dev/guide/quick-start.html
模板

拉取后 开箱即用
模板地点👉 https://github.com/gitboyzcf/uni-preset-vue3-vite
敬请等待

后续还会有新功能接入当前模板,敬请等待…


到这里就竣事了,后续还会更新 前端 系列干系,还请连续关注!
感谢阅读,如有错误可以在下方品评区留言哦!!!



保举文章👇
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表