上一篇文章描述了如何使用其他手段实现路由守卫
本文将深入探讨如何在基于这些技术栈的小程序项目中引入状态管理插件
一、了解 Pinia
Pinia 是一个全新的 Vue 状态管理库,旨在替代 Vuex 成为 Vue 3 应用程序中的首选状态管理解决方案。它提供了更加简洁的 API 和更好的 TypeScript 支持。
通过结合使用 UniApp、Vue 3、TypeScript 和 Pinia,开发者可以在钉钉小程序等多端平台上快速构建高效、类型安全的应用程序。Pinia 提供了更灵活和强大的状态管理功能,使得状态管理变得更加直观和易于维护。
二、集成Pinia
官方地址:开始 | Pinia
1. 由于我们使用的是pnpm作为包管理器,所以为了保持一致,我们使用pnpm进行安装
注意这个指令哦!!!不听话的就去最后看避坑指南吧!!!
pnpm install pinia@2.0.36
2. 在main.ts中引用pinia
import { createSSRApp } from "vue";
import App from "./App.vue";
import useRouterInterceptor from './permission'
import { createPinia } from 'pinia'
export function createApp() {
const app = createSSRApp(App);
app.use(createPinia)
useRouterInterceptor()
return {
app,
};
}
三、使用Pinia
1. 创建src/store目录
2. 创建 src/store/counter.ts 文件
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0, name: 'Eduardo' }),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++
},
},
})
3. 测试功能
<template>
<view class="content">
<view class="text-area">
<text class="content">{{ countStore.count }}- {{countStore.doubleCount}}</text>
<view style="width: 100%">
<ant-button @tap="increment" type="primary" size="large">点击加1</ant-button>
</view>
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import {useCounterStore} from "@/store/counter";
const countStore = useCounterStore()
const increment = () => {
countStore.increment()
}
</script>
<style>
</style>
四、踩坑指南
如果你有以下报错:
[plugin:uni:mp-main-js] Package subpath './dist/pinia.mjs' is not defined by "exports" in /Users/codels/Downloads/uni-preset-vue-vite-ts/node_modules/pinia/package.json
这意味着你在项目中尝试使用 pinia
时,指定了一个不被支持的入口点(即 ./dist/pinia.mjs
),而这个入口点并未在 pinia
的 package.json
文件的 "exports"
字段中声明。
这是AI给我的错误分析,毫无用处,浪费我情绪!
开开开,直接说解决方案:
请看官方VCR:
uni-app 内置了 Pinia 。Vue 2 项目暂不支持
注意事项
使用
HBuilder X
HBuilder X 已内置了 Pinia,无需手动安装,按照下方示例使用即可。
App 升级时,如果之前使用
HBuilder X 版本 < 4.14
打包,现在使用HBuilder X 版本 >= 4.14
,更新时需要整包更新不可使用wgt更新(在4.14
时升级了vue
版本,低版本的基座和高版本 wgt 资源包会导致使用 Pinia 时报错)使用
CLI
4.14 之前
:执行yarn add pinia@2.0.36
或npm install pinia@2.0.36
安装,要固定版本4.14 之后
:执行yarn add pinia
或npm install pinia
安装,可不指定版本- 文档地址:状态管理 Pinia | uni-app官网
所以我们只需要...
# 卸载安装版本
pnpm uninstall pinia
# 安装兼容版本
pnpm install pinia@2.0.36
最后附地址:
https://gitcode.com/gmstudio/uni-vue3-ts-template
分支:pinia