Young's blog Young's blog
首页
Spring
  • 前端文章1

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Young

首页
Spring
  • 前端文章1

    • JavaScript
  • 学习笔记

    • 《JavaScript教程》
    • 《JavaScript高级程序设计》
    • 《ES6 教程》
    • 《Vue》
    • 《React》
    • 《TypeScript 从零实现 axios》
    • 《Git》
    • TypeScript
    • JS设计模式总结
  • HTML
  • CSS
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • ES7、ES8、ES9、ES10、ES11、ES12都增加了哪些新特性
  • 听说后端的你在学 React
  • uniApp新模式 - 使用Vue3 + Vite4 + Pinia + Axios技术栈构建
    • 背景
    • 版本号
    • 项目目录结构
    • 开发流程
      • 安装
      • 运行
      • 安装 pinia
      • 使用 pinia
      • pinia 数据持久化
      • 安装 axios
      • 使用 axios
      • 配置 vue 自动导入
      • 安装 uni-ui
      • 使用 uni-ui
  • 前端监控体系搭建
  • web
andanyang
2023-07-10
目录

uniApp新模式 - 使用Vue3 + Vite4 + Pinia + Axios技术栈构建

# 背景

使用Vue3 + Vite4 + Pinia + Axios + Vscode模式开发之后,感叹真香!不用再单独去下载HBuilderX。废话不多说,直接上干货!

# 版本号

  • node: v16.18.0
  • vue: ^3.3.4,
  • vite: 4.1.4
  • sass: ^1.62.1
  • pinia: 2.0.36
  • pinia-plugin-unistorage: ^0.0.17
  • axios: ^1.4.0
  • axios-miniprogram-adapter: ^0.3.5
  • unplugin-auto-import: ^0.16.4

如遇到问题,请检查版本号是否一致!!!

# 项目目录结构

└── src # 主目录
    ├── api # 存放所有api接口文件
    │   ├── user.js # 用户接口
    ├── config # 配置文件
    │   ├── net.config.js # axios请求配置
    ├── pinia-store # 配置文件
    │   ├── user.js # axios请求配置
    ├── utils # 工具类文件
    │   ├── request.js # axios请求封装
1
2
3
4
5
6
7
8
9

# 开发流程

建议去 uni-preset-vue (opens new window) 仓库下载vite分支 zip 包,熟练 ts 的童鞋下载vite-ts

# 安装

  • 下载之后进入项目
cd uni-preset-vue
1
  • 安装依赖
# pnpm
pnpm install
# yarn
yarn
# npm
npm i
1
2
3
4
5
6

# 运行

pnpm dev:mp-weixin
1

打开微信开发者工具,找到dist/dev/mp-weixin运行,可以看到默认的页面

# 安装 pinia

pnpm add pinia
1

# 使用 pinia

在src目录下构建 pinia-store/user.js文件

/**
 * @description 用户信息数据持久化
 */
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
    state() {
        return {
            userInfo: {}
        }
    },
    actions: {
        setUserInfo(data) {
            this.userInfo = data
        }
    }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  • 修改main.js文件
import {
	createSSRApp
} from "vue";
import * as Pinia from 'pinia';
import App from "./App.vue";
export function createApp() {
    const app = createSSRApp(App);
    const store = Pinia.createPinia();
    app.use(store);

    return {
        app,
        Pinia
    };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# pinia 数据持久化

安装pinia-plugin-unistorage

pnpm add pinia-plugin-unistorage
1

修改main.js文件, 增加如下代码:

// pinia数据持久化
import { createUnistorage } from 'pinia-plugin-unistorage'
store.use(createUnistorage());
app.use(store);
1
2
3
4

完整代码如下:

import { createSSRApp } from "vue";

import * as Pinia from 'pinia';
// pinia数据持久化
import { createUnistorage } from 'pinia-plugin-unistorage'
import App from "./App.vue";
export function createApp() {
    const app = createSSRApp(App);

    const store = Pinia.createPinia();
    store.use(createUnistorage());
    app.use(store);

    return {
        app,
        Pinia
    };
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

在页面中使用:

<script setup>
    import { useUserStore } from '@/pinia/user.js'
    const user = useUserStore()

    // 设置用户信息
    const data = { userName: 'snail' }
    user.setUser(data)
    // 打印用户信息
    console.log(user.userInfo)
</script>
1
2
3
4
5
6
7
8
9
10

# 安装 axios

pnpm add axios
1

适配小程序,需要另外安装axios-miniprogram-adapter插件

pnpm add axios-miniprogram-adapter
1

# 使用 axios

在utils创建utils/request.js文件

import axios from 'axios';
import mpAdapter from "axios-miniprogram-adapter";
axios.defaults.adapter = mpAdapter;
import { netConfig } from '@/config/net.config';
const { baseURL, contentType, requestTimeout, successCode } = netConfig;

let tokenLose = true;

const instance = axios.create({
  baseURL,
  timeout: requestTimeout,
  headers: {
    'Content-Type': contentType,
  },
});

// request interceptor
instance.interceptors.request.use(
  (config) => {
    // do something before request is sent
    return config;
  },
  (error) => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
instance.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */
  (response) => {
    const res = response.data;

    // 请求出错处理
    // -1 超时、token过期或者没有获得授权
    if (res.status === -1 && tokenLose) {
      tokenLose = false;
      uni.showToast({
        title: '服务器异常',
        duration: 2000
    });

      return Promise.reject(res);
    }
    if (successCode.indexOf(res.status) !== -1) {
      return Promise.reject(res);
    }
    return res;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default instance;
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

其中net.config.js文件需要在src/config目录下创建,完整代码如下:

/**
 * @description 配置axios请求基础信息
 * @author hu-snail 1217437592@qq.com
 */
export const netConfig = {
    // axios 基础url地址
    baseURL: 'https://xxx.cn/api',
    // 为开发服务器配置 CORS。默认启用并允许任何源,传递一个 选项对象 来调整行为或设为 false 表示禁用
    cors: true,
    // 根据后端定义配置
    contentType: 'application/json;charset=UTF-8',
    //消息框消失时间
    messageDuration: 3000,
    //最长请求时间
    requestTimeout: 30000,
    //操作正常code,支持String、Array、int多种类型
    successCode: [200, 0],
    //登录失效code
    invalidCode: -1,
    //无权限code
    noPermissionCode: -1,
  };
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

在src目录下创建src/api/user.jsapi 文件

import request from '@/utils/request'

/**
 * @description 授权登录
 * @param {*} data
 */
export function wxLogin(data) {
	return request({
		url: '/wx/code2Session',
		method: 'post',
		params: {},
		data
	})
}

/**
 * @description 获取手机号
 * @param {*} data
 */
export function getPhoneNumber(data) {
	return request({
		url: '/wx/getPhoneNumber',
		method: 'post',
		params: {},
		data
	})
}
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

在页面中使用

<script setup>
    import { wxLogin, getPhoneNumber } from '@/api/user.js'
      /**
     * @description 微信登录
     */
    const onWxLogin = async () => {
        uni.login({
            provider: 'weixin',
            success: loginRes => {
                state.wxInfo = loginRes
                const jsCode = loginRes.code
                wxLogin({jsCode}).then((res) => {
                    const { openId } = res.data
                    user.setUserInfo({ openId })
                })
            }
        })
    }

</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 配置 vue 自动导入

安装unplugin-auto-import插件

pnpm add unplugin-auto-import -D
1

修改vite.config.js文件:

import AutoImport from 'unplugin-auto-import/vite'
 plugins: [
    AutoImport({
      imports: ["vue"]
    })
  ],
1
2
3
4
5
6

页面中使用,需要注意的事每次导入新的 vue 指令,需要重新运行!!

<script setup>
     onBeforeMount(() => {
         console.log('----onBeforeMount---')
     })
</script>
1
2
3
4
5

# 安装 uni-ui

pnpm add @dcloudio/uni-ui
1

# 使用 uni-ui

修改pages.json文件,增加如下代码:

"easycom": {
        "autoscan": true,
        "custom": {
                "^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue"
        }
},
1
2
3
4
5
6

在页面中使用

<template>
  <uni-icons type="bars" size="16"></uni-icons>
</template>
1
2
3

到此已基本可以完成程序的开发,其他功能按照自己的需求做增删改查即可!

编辑 (opens new window)
#前端
上次更新: 2024/04/19, 08:52:45
听说后端的你在学 React
前端监控体系搭建

← 听说后端的你在学 React 前端监控体系搭建→

最近更新
01
idea 热部署插件 JRebel 安装及破解,不生效问题解决
04-10
02
spark中代码的执行位置(Driver or Executer)
12-12
03
大数据技术之 SparkStreaming
12-12
更多文章>
Theme by Vdoing | Copyright © 2019-2024 Young | MIT License
浙ICP备20002744号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式