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中调用接口,万变不离其宗,都可以根据这种简单的例子来实现

相关推荐
zttbee1 分钟前
前端测试内容
前端
2603_965896625 分钟前
async/await|JS同步写法解决异步终极方案
前端·javascript
A24207349302 小时前
TCP 三次握手与四次挥手:从原理到状态机一次讲清
前端
GreenTea9 小时前
GrokBot 核心成员 Lauren Tan:每月交付 2000 个 PR 的人,是怎么用 AI 的
前端·后端·架构
mCell10 小时前
用 Knip 清理 AI Coding 留下的冗余代码
前端·ai编程·前端工程化
笃行35011 小时前
使用Rokid AIUI做了一个童年推箱子游戏
前端
excel12 小时前
前端加密的作用与使用场景
前端
计算机魔术师13 小时前
纽约时报版权诉讼披露:微软高管内部称训练 AI 是人类历史上最大规模劳动窃取
前端
去伪存真14 小时前
大模型的参数量为什么那么大?
前端·人工智能
IT_陈寒14 小时前
Java空指针这次真把我坑惨了
前端·人工智能·后端