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 }
})
相关推荐
用户823067907506 天前
Vuex 项目实战完整模板
vuex
abigale038 天前
低代码平台前端功能优化与实现
低代码·图片上传·vuex·ant-design
Irene199111 天前
Vue 2、Vue 3 、Vuex 3、Vuex 4 和 Pinia 响应式丢失场景及解决方案
vue·pinia·vuex
SuperEugene13 天前
Vue3 Pinia 状态管理规范:状态拆分、Actions 写法、持久化实战,避坑状态污染|状态管理与路由规范篇
前端·javascript·vue.js·前端框架·pinia
optimistic_chen15 天前
【Vue3入门】Pinia 状态管理 和 ElementPlus组件库
前端·javascript·vue.js·elementui·pinia·组件
Irene199118 天前
Vuex版本演进与核心特性对比(附:Vuex 4 与 Pinia 核心区别对比)
pinia·vuex·数据流
Irene199119 天前
对比总结:Vue3中的 watch 和 Pinia中的 $subscribe
vue.js·pinia·watch·subscribe
这是个栗子20 天前
【Vue3项目】电商前台项目(四)
前端·vue.js·pinia·表单校验·面包屑导航
梵得儿SHI21 天前
Vue3 实战:从 0 搭建企业级后台管理系统(Router+Pinia+Axios+Element Plus 全整合)
前端·javascript·vue.js·pinia状态管理·项目初始化·页面路由配置·后台首页布局
还是大剑师兰特22 天前
Pinia在Vue3中的应用部署与使用,包括持久化方案
pinia·大剑师