Table of contents
1. Background
After using Vue3 + Vite4 + Pinia + Axios + Vscode mode to develop, I sighed that it tastes great! No need to download HBuilderX separately. Without further ado, let’s get straight to the practical stuff!
2. Version number
- node: v16.18.0
- vue: ^3.3.4,
- quickly: 4.1.4
- sass: ^1.62.1
- install: 2.0.36
- pineapple-plugin-unistorage: ^0.0.17
- axios: ^1.4.0
- axios-miniprogram-adapter: ^0.3.5
- unplugin-auto-import: ^0.16.4
If you encounter problems, please check whether the version numbers are consistent!!!
3. Project directory structure
└── src # Main directory
├── api # Stores all api interface files
│ ├── user.js # User interface
├── config # Configuration file
│ ├── net.config.js # axios request configuration
├── pinia-store # Configuration file
│ ├── user.js # axios request configuration
├── utils # Tool class file
│ ├── request.js # axios request encapsulation
4. Development process
It is recommended to go to the uni-preset-vue warehouse to download the zip package of the vite branch, and for children who are skilled in ts, download vite-ts
4.1, installation
- After downloading, enter the project
cd uni-preset-vue
- Install dependencies
# pnpm
pnpm install
# yarn
yarn
# npm
npm i
- run
pnpm dev:mp-weixin
Open the WeChat developer tool, find dist/dev/mp-weixin and run it. You can see the default page.
- Install pinia
pnpm add pinia
- Use pinia
to build the pinia-store/user.js file in the src directory
/**
* @description 用户信息数据持久化
*/
import {
defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state() {
return {
userInfo: {
}
}
},
actions: {
setUserInfo(data) {
this.userInfo = data
}
}
})
- Modify main.js file
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
};
}
- pinia data persistence
install pinia-plugin-unistorage
pnpm add pinia-plugin-unistorage
Modify the main.js file and add the following code:
// pinia数据持久化
import {
createUnistorage } from 'pinia-plugin-unistorage'
store.use(createUnistorage());
app.use(store);
The complete code is as follows:
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
};
}
Use in the page:
<script setup>
import {
useUserStore } from '@/pinia/user.js'
const user = useUserStore()
// 设置用户信息
const data = {
userName: 'snail' }
user.setUser(data)
// 打印用户信息
console.log(user.userInfo)
</script>
- Install axios
pnpm add axios
To adapt to mini programs, you need to install the axios-miniprogram-adapter plug-in separately.
pnpm add axios-miniprogram-adapter
4.2, using axios
Create the utils/request.js file in utils
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;
The net.config.js file needs to be created in the src/config directory. The complete code is as follows:
/**
* @description 配置axios请求基础信息
* @author hu-snail [email protected]
*/
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,
};
Create the src/api/user.jsapi file in the src directory
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
})
}
Use in the page
<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>
4.3, configure vue to automatically import
Install unplugin-auto-import plug-in
pnpm add unplugin-auto-import -D
Modify the vite.config.js file:
import AutoImport from 'unplugin-auto-import/vite'
plugins: [
AutoImport({
imports: ["vue"]
})
],
When used in the page, you need to pay attention to the fact that every time you import a new vue instruction, you need to re-run it! !
<script setup>
onBeforeMount(() => {
console.log('----onBeforeMount---')
})
</script>
- Ansou uni-ui
pnpm add @dcloudio/uni-ui
- Use uni-ui
to modify the pages.json file and add the following code:
"easycom": {
"autoscan": true,
"custom": {
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue"
}
},
Use in the page
<template>
<uni-icons type="bars" size="16"></uni-icons>
</template>
At this point, the development of the program can basically be completed. Other functions can be added, deleted, modified and checked according to your own needs.