Vue3 + Vite4 + Pinia + Axios Project Setup and Usage Guide
This guide walks through setting up a Vue3 project with Vite4, Pinia, and Axios—including version specifications, directory structure, installation commands, Pinia persistence, Axios configuration, auto‑import setup, and Uni‑UI integration—providing complete code snippets for each step.
Background : The tutorial demonstrates how to develop a Vue3 application using Vite4, Pinia, and Axios, eliminating the need for HBuilderX.
Version Numbers :
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
Project Directory Structure :
└── src # 主目录
├── api # 存放所有api接口文件
│ ├── user.js # 用户接口
├── config # 配置文件
│ ├── net.config.js # axios请求配置
├── pinia-store # 配置文件
│ ├── user.js # axios请求配置
├── utils # 工具类文件
│ ├── request.js # axios请求封装Development Process :
Download the vite or vite-ts branch zip from the uni-preset-vue repository.
Installation :
cd uni-preset-vue # pnpm
pnpm install
# yarn
yarn
# npm
npm iRun the project :
pnpm dev:mp-weixinOpen the WeChat DevTools and locate dist/dev/mp-weixin to view the default page.
Install Pinia :
pnpm add piniaUse Pinia – create src/pinia-store/user.js :
/**
* @description 用户信息数据持久化
*/
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
state() {
return {
userInfo: {}
}
},
actions: {
setUserInfo(data) {
this.userInfo = data
}
}
})Modify main.js to register the store:
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 Persistence – install pinia-plugin-unistorage and add to main.js :
// pinia数据持久化
import { createUnistorage } from 'pinia-plugin-unistorage'
store.use(createUnistorage());
app.use(store);Full main.js after adding persistence:
import { createSSRApp } from "vue";
import * as Pinia from '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 };
}Example usage in a page:
<script setup>
import { useUserStore } from '@/pinia/user.js'
const user = useUserStore()
const data = { userName: 'snail' }
user.setUserInfo(data)
console.log(user.userInfo)
</script>Install Axios and the mini‑program adapter:
pnpm add axios pnpm add axios-miniprogram-adapterCreate src/utils/request.js to configure Axios with the adapter and interceptors:
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 },
});
instance.interceptors.request.use(config => config, error => Promise.reject(error));
instance.interceptors.response.use(response => {
const res = response.data;
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 => Promise.reject(error));
export default instance;Define src/config/net.config.js with base request settings:
/**
* @description 配置axios请求基础信息
*/
export const netConfig = {
baseURL: 'https://xxx.cn/api',
cors: true,
contentType: 'application/json;charset=UTF-8',
messageDuration: 3000,
requestTimeout: 30000,
successCode: [200, 0],
invalidCode: -1,
noPermissionCode: -1,
};Create API file src/api/user.js :
import request from '@/utils/request';
/**
* @description 授权登录
*/
export function wxLogin(data) {
return request({ url: '/wx/code2Session', method: 'post', params: {}, data });
}
/**
* @description 获取手机号
*/
export function getPhoneNumber(data) {
return request({ url: '/wx/getPhoneNumber', method: 'post', params: {}, data });
}Use the API in a page:
<script setup>
import { wxLogin, getPhoneNumber } from '@/api/user.js';
const onWxLogin = async () => {
uni.login({
provider: 'weixin',
success: loginRes => {
const jsCode = loginRes.code;
wxLogin({ jsCode }).then(res => {
const { openId } = res.data;
user.setUserInfo({ openId });
});
}
});
};
</script>Configure Vue Auto‑Import by installing unplugin-auto-import and adding it to vite.config.js :
pnpm add unplugin-auto-import -D import AutoImport from 'unplugin-auto-import/vite'
plugins: [
AutoImport({ imports: ["vue"] })
],Note: After adding new Vue directives, re‑run the dev server.
Install and Use uni‑ui :
pnpm add @dcloudio/uni-uiAdd auto‑scan configuration to pages.json :
"easycom": {
"autoscan": true,
"custom": {
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue"
}
},Use a uni‑ui component in a page template:
<template>
<uni-icons type="bars" size="16"></uni-icons>
</template>Following these steps provides a functional Vue3 + Vite4 + Pinia + Axios project ready for further feature development.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.