background
After using Vue3 + Vite4 + Pinia + Axios
the + Vscode
model to develop, I am really impressed! No need to download it separately HBuilderX
. Without further ado, let's go straight to the dry goods!
version number
- node:
v16.18.0
- vue:
^3.3.4
, - fast:
4.1.4
- sass:
^1.62.1
- beans:
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!!!
Project directory structure
└── src # 主目录
├── api # 存放所有api接口文件
│ ├── user.js # 用户接口
├── config # 配置文件
│ ├── net.config.js # axios请求配置
├── pinia-store # 配置文件
│ ├── user.js # axios请求配置
├── utils # 工具类文件
│ ├── request.js # axios请求封装
Development Process
It is recommended to go to the uni-preset-vue warehouse to download vite
the branch zip package, and download the children's shoes skilled in tsvite-ts
Install
- Enter the project after downloading
cd uni-preset-vue
- install dependencies
# pnpm
pnpm install
# yarn
yarn
# npm
npm i
run
pnpm dev:mp-weixin
Open the WeChat developer tools, find dist/dev/mp-weixin
the run, you can see the default page
install pinia
pnpm add pinia
use pinia
src
build pinia-store/user.js
files 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
Installpinia-plugin-unistorage
pnpm add pinia-plugin-unistorage
Modify main.js
the 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
};
}
In the page use:
<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 applets, additional axios-miniprogram-adapter
plug-ins need to be installed
pnpm add axios-miniprogram-adapter
use axios
while utils
creating utils/request.js
the file
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
files need to src/config
be created in the directory, the complete code is as follows:
/**
* @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,
};
src
Create src/api/user.js
the api file in the 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>
Configure vue to automatically import
install unplugin-auto-import
plugin
pnpm add unplugin-auto-import -D
Modify vite.config.js
the file:
import AutoImport from 'unplugin-auto-import/vite'
plugins: [
AutoImport({
imports: ["vue"]
})
],
页面中使用,需要注意的事每次导入新的vue指令,需要重新运行!!
<script setup>
onBeforeMount(() => () => {
console.log('----onBeforeMount---')
})
</script>
安装uni-ui
pnpm add @dcloudio/uni-ui
使用uni-ui
修改pages.json
文件,增加如下代码:
"easycom": {
"autoscan": true,
"custom": {
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue"
}
},
在页面中使用
<template>
<uni-icons type="bars" size="16"></uni-icons>
</template>
到此已基本可以完成程序的开发,其他功能按照自己的需求做增删改查即可!