pinia简单使用

文章介绍了如何安装和使用Pinia作为Vue应用的状态管理库,包括在main.js中引入,创建模块化的store,以及使用storeToRefs和$patch方法进行数据操作。此外,还提到了通过pinia-plugin-persist实现状态持久化存储,确保数据在页面刷新后仍能保留。
摘要由CSDN通过智能技术生成

安装Pinia 状态管理库

Pinia地址

npm install pinia

在main.js中引入

import { createPinia } from 'pinia'

const pinia = createPinia()

const app = createApp(App)

app.use(pinia)

store/figure.js

import {defineStore} from 'pinia';
export const figure=  defineStore('figure',{
  state:()=>{
    return {
      names : 'ying',
      age : 18 
    }
  },
  getters:{
    changeMoney(){
      return this.money + 500
    }
  },
  actions:{
    addMoney(value){
      this.money += value
    }
  }
})

pinia分模块

store文件夹下创建js文件,每个js文件就是一个模块,如:

// user.js
import {defineStore} from 'pinia';
export const user =  defineStore('user',{
  state:()=>{
    return {
      names : 'fan',
      age : 18 ,
    }
  },
  getters:{    
  },
  actions:{ 
  }
})

pinia简单用法

<template>
  <button @click="changes">修改</button>
  <div>姓名:{{ names }}</div>
  <div>年龄:{{ age }}</div>
  <div>money:{{ changeMoney }}</div>
  <button @click="btn">actions</button>
  <button @click="reset">重置</button>
</template>
<script setup>
// 用那个模块引入那个模块
import { figure} from '@/store/figure';
import {storeToRefs} from 'pinia';
const store = figure();

let {names, age, changeMoney} = storeToRefs(store)

const changeAge = ()=>{
  // 第一种修改方法
  // age.value +=1

  // 第二种修改方法 可以不用 let { names ...} = storeToRefs(store)  
  // 直接  {{ state.age }}
  store.$patch(state=>{
    state.age+=1
    state.money += 500
  })
}
// 触发actions
const btn = ()=>{
  store.addMoney(500)
}
// 重置
const reset = ()=>{
  store.$reset()
}
</script>

pinia持久化存储

npm install pinia-plugin-persist

main.js

import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'
const pinia = createPinia()

const app = createApp(App)

pinia.use(piniaPersist)

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

xxx.js文件中

actions:{ 
},
persist:{
   enabled: true,
   // 默认是sessionStorage 即关闭标签页就会清除缓存
   strategies: [{
     key:'cs',
     storage: localStorage 
   }]
 }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

瞌睡凡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值