Vue3学习-Pinia 集中式状态管理工具

安装 Pinia

js 复制代码
npm i pinia

Pinia 集中式状态管理工具官网 传送门

引入 Pinia

js 复制代码
//引入
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App);
app.use(pinia);

使用

js 复制代码
// store 注册
import { defineStore } from "pinia";
export const useAStore = defineStore('a',{
    state(){
        return { a:1 }
    },
    getters: {
	   doubleCount: (state) => state.a * 2,
	},
	actions: {
	    increment(val) {
	      this.a = val
	    },
	},
})
// 组件获取
import { useAStore,storeToRefs } from '@/store/a'
const aStore = useAStore()
// 监听aStore 变化
aStore.$subscribe((mutate,state) => {
	console.log(mutate); // 行为
	console.log(state); // 改变后数据
});
let { a } = storeToRefs(aStore ) //store响应式数据,用于修改实时改变的值
console.log(aStore)
//修改
aStore.a += 1; // 单个
aStore.$patch({ // 批量
	a:2
});
aStore.increment(3)
// 获取getter
aStore.doubleCount()

组合式使用

js 复制代码
import { reactive, ref } from "vue";
import { defineStore } from "pinia";
export const useAStore = defineStore('a',{
    let a = ref('1')
    async function addAFun(){
    	a++
    }
    return { a,addAFun }
})
相关推荐
陆业聪11 天前
AI Bug修复与测试生成:从崩溃日志到修复PR的自动化 | AI提效Android开发(5)
状态管理·微前端·大前端
吴声子夜歌18 天前
Vue3——Pinia状态管理
javascript·vue.js·pinia
Thanks_ks20 天前
软件系统中的熵增定律:技术债的形成与重构的艺术
软件工程·敏捷开发·架构设计·状态管理·代码重构·技术债·康威定律
梦想不只是梦与想21 天前
flutter中 InheritedWidget 实现原理
flutter·状态管理
曲幽1 个月前
Vue 3 组件通信,别只会用 Props 和 Emits 了,这几个狠活儿你得看看
vue3·inject·provide·pinia·v-model·props·mitt·emit
╰つ栺尖篴夢ゞ1 个月前
HarmonyOS Next面试题之装饰器@Prop与@Link的区别和使用
状态管理·link·组件通信·prop·v1装饰器
travel_wsy1 个月前
vue Pinia 状态管理库
前端·pinia
用户823067907502 个月前
Vuex 项目实战完整模板
vuex
abigale032 个月前
低代码平台前端功能优化与实现
低代码·图片上传·vuex·ant-design