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";