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 }
})
相关推荐
曲幽13 天前
Vue 3 组件通信,别只会用 Props 和 Emits 了,这几个狠活儿你得看看
vue3·inject·provide·pinia·v-model·props·mitt·emit
╰つ栺尖篴夢ゞ18 天前
HarmonyOS Next面试题之装饰器@Prop与@Link的区别和使用
状态管理·link·组件通信·prop·v1装饰器
travel_wsy20 天前
vue Pinia 状态管理库
前端·pinia
用户823067907501 个月前
Vuex 项目实战完整模板
vuex
abigale031 个月前
低代码平台前端功能优化与实现
低代码·图片上传·vuex·ant-design
Irene19911 个月前
Vue 2、Vue 3 、Vuex 3、Vuex 4 和 Pinia 响应式丢失场景及解决方案
vue·pinia·vuex
SuperEugene1 个月前
Vue3 Pinia 状态管理规范:状态拆分、Actions 写法、持久化实战,避坑状态污染|状态管理与路由规范篇
前端·javascript·vue.js·前端框架·pinia
optimistic_chen1 个月前
【Vue3入门】Pinia 状态管理 和 ElementPlus组件库
前端·javascript·vue.js·elementui·pinia·组件
Irene19911 个月前
Vuex版本演进与核心特性对比(附:Vuex 4 与 Pinia 核心区别对比)
pinia·vuex·数据流
Irene19911 个月前
对比总结:Vue3中的 watch 和 Pinia中的 $subscribe
vue.js·pinia·watch·subscribe