vue Pinia 状态管理库

Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。与 Vuex 相比,Pinia 不仅提供了一个更简单的 API,也提供了符合组合式 API 风格的 API,最重要的是,搭配 TypeScript 一起使用时有非常可靠的类型推断支持。今天主要记录一下在Vue3下使用Pinia的使用情况:

一、安装

yarn add pinia

或者

npm install pinia

二、创建Pinia

复制代码
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'

const pinia = createPinia()

createApp(App).use(pinia).mount('#app')

三、定义属性和方法

TypeScript 复制代码
import { defineStore } from 'pinia'

export const useTemplate = defineStore('useTemplate',{
    state:() => ({
        count:0
    }),
    getters:{
        doubleCount:(state) =>{
            state.count * 2
        },
        threeCount:(state) => state.count * 3
    },
    actions:{
        addCount(){
            this.count ++
        },
        minusCount(){
            this.count --
        }
    }
})

在state中定义属性,和data类似,getters是定义计算属性,和computed类似,actions定义方法,和methods类似,所以上面的例子也可换种写法:

TypeScript 复制代码
export const useTemplate = defineStore('useTemplate',() =>{
    const count = ref(0)
    const doubleCount = computed(() => count1.value * 2)
    const threeCount = computed(() => count1.value * 3)
    function addCount(){
        count1.value ++
    }
    const minusCount = () =>{
        count1.value --
    }
    return {count,doubleCount,threeCount,addCount,minusCount}
})

四、使用

import { useTemplate} from '@/stores/useStores'

TypeScript 复制代码
import { useTemplate,useTemplate2 } from '@/stores/useStores'

const store = useTemplate()

//修改属性值
//方法1
store.count += 1
//方法2
store.addCount()
//方法3,重置属性值
store.$reset()

以上就是pinia的简单使用方法,更多复杂的,比如在actions中调用接口,万变不离其宗,都可以根据这种简单的例子来实现

相关推荐
guslegend44 分钟前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
海码事务所1 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端
田威AI1 小时前
图片内文字翻译的规格:输入输出、保真、自动化、时间与费用
前端·计算机视觉
不可能片场2 小时前
命令行中文变问号 我用环境变量救了场
前端·electron
lerhxx2 小时前
AI 应用中的上下文管理 —— 从"上下文窗口"到"分层压缩"的工程实践
前端·javascript
骑着蜗牛撵大象3272 小时前
多 Agent 分治协作:MapReduce 模式下的并行扇出与结果归并
前端
用户55318297322 小时前
Flutter iOS 热更新深入 Dart VM:读懂函数入口、解释执行与调用桥接
前端
前端snow2 小时前
为什么大厂要用Postgres + mogodb的框架?
前端
运维有小邓12 小时前
2026年主流AD域管理软件有哪些?
前端
Mickey同学2 小时前
提示词注入:AI 时代的「SQL 注入」
前端