vue3 pinia的使用及持久化存储

1.使用pinia操作步骤:

1、安装

npm install pinia -s

2、创建文件

index文件(存储大仓库)

import { createPinia } from 'pinia'
const pinia = createPinia()
//对外暴露:入口文件需要安装仓库
export default pinia

3、引入 

4.、使用

 创建modules文件夹,存储小仓库

//创建用户相关的小仓库
import { defineStore } from 'pinia'
// store的options API写法
export const Store = defineStore('唯一的命名', {
     state:()=>{
        return {
            counter: 0
        }
     },
    actions:{ 想要使用state中的数据----this.counter },
    getters:{
        peiCount: ({ counter }) => {
          return counter * 10
        }
    }
})
// store的composition API写法
import { ref, computed } from 'vue'

export const Store = defineStore('唯一的命名', ()=>{
    const counter = ref(0)
    const peiCount = computed(()=>counter * 10)

    return { counter, peiCount }
})

5.、修改数据

在组件中调用---(传统的调用)

<script setup>
// 从状态层导出指定模块
import useStoreModule from '../store/module/user'
import { storeToRefs } from 'pinia'

// 使用pinia
const useStore = useStoreModule()

// pinia 使用---同步修改数据
const { userList, count, peiCount, peiSum } = storeToRefs(useStore)

// 直接使用方法
useStore.getList()

// 修改pinia数据
const addNum = () => {
  // 第一种方式
  useStore.count++

  // 第二种方式---使用storeToRefs解构出来的
  count.value++

  // 第三种方式
  useStore.$patch({
     count: useStore.count + 1
  })

  // 第四种方式---箭头函数
  useStore.$patch((state) => {
     state.count++
  })
}
</script>

外部文件 与 App.vue文件 同级的文件) 使用仓库步骤

import useUserStore from './store/modules/user'   -------引入小仓库

import pinia from './store'                                          -------引入大仓库

const userStore = useUserStore(pinia)                   -------使用仓库数据

2、 持久化存储

1. 安装插件

npm install pinia-plugin-persist -s

 2. 引入插件

 3. 使用插件

方式1:默认保存

下面这种写法会将当前模块中的所有数据都进行持久化保存,默认保存在 sessionStorage 中, key 为模块 id,刷新页面不需要手动读取数据,插件会自动读取。

import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    name: null,
    age: null,
    sex: null,
  }),
  persist: {
    enabled: true // true 表示开启持久化保存
  }
})
 方式2:设置 key 、保存方式
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    name: null,
    age: null,
    sex: null,
  }),
  persist: {
    key: 'userName', // 保存的 key 名
    storage: sessionStorage, // 保存方式
    paths: ['name'] // 保存state具体数据, 不指定则全部保存
  },
})

3、小程序 pinia持久化

persist 配置

    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          uni.setStorageSync(key, value)
        },
      },
    },

4、vuex的持久化

import createPersistedState from "vuex-persistedstate";

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值