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 }
})
相关推荐
Irene19919 小时前
Pinia 使用详解(附:如何查看或区分项目使用的是 Pinia 还是 Vuex 4)
pinia·vuex
啥都不懂的小小白2 天前
Vue Ajax与状态管理完全指南:从数据请求到全局状态控制
vue.js·ajax·vuex·插槽系统
夏小鱼的blog10 天前
【HarmonyOS应用开发入门】第六期:状态管理V2入门 - 2
harmonyos·状态管理
在西安放羊的牛油果13 天前
浅谈 storeToRefs
前端·typescript·vuex
梵得儿SHI15 天前
Pinia 状态管理从入门到精通:基础 / 核心特性 / 多 Store / 持久化全实战(Vue2/Vue3 适配)
javascript·vue.js·ecmascript·pinia·态持久化存储方案·实战避坑指南·ue2/vue3项目开发
夏小鱼的blog16 天前
【HarmonyOS应用开发入门】第五期:状态管理V2入门 - 1
harmonyos·状态管理
凯小默1 个月前
【TypeScript+Vue3+Vite+Vue-router+Vuex+Mock 进行 WEB 前端项目实战】学习笔记共 89 篇(完结)
typescript·echarts·mock·vue3·vite·vuex·vue-router
灵感菇_1 个月前
Flutter Riverpod 完整教程:从入门到实战
前端·flutter·ui·状态管理
盛夏绽放2 个月前
新手入门:实现聚焦式主题切换动效(Vue3 + Pinia + View Transitions)
前端·vue3·pinia·聚焦式主题切换
小时前端2 个月前
Vuex 响应式原理剖析:构建可靠的前端状态管理
前端·面试·vuex