pinia快速使用

发布时间 2023-12-26 21:11:47作者: Ewar-k

安装

pnpm add pinia

创建一个pinia实例(根store)并将其传递给应用:

import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'

const pinia = createPinia()
const app = createApp(App)

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

定义Store与使用

通过defineStore()定义,它有两个参数:

  • 第一个参数是一个独一无二的名字
  • 第二个参数是可接受的两类值:Setup函数Option对象

Setup函数

该写法与 Vue 组合式 API 的 setup 函数 相似,我们可以传入一个函数,该函数定义了一些响应式属性和方法,并且返回一个带有我们想暴露出去的属性和方法的对象。

import {ref} from 'vue'
import { defineStore } from 'pinia'
export const userCounterStore = defineStore("counter",()=>{
    //state
    const count =  ref(0)
    //actions
    function increment(){
        count.value++
    }
    //getter
    cont doubleCount = computed(()=>count.value*2)
    return{
        count,
        increment,
        doubleCount
    }
})

Option对象

与vue的选项式API类似,可以传入一个带有stateactionsgetters属性的Option对象

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

认为 state 是 store 的数据 (data),getters 是 store 的计算属性 (computed),而 actions 则是方法 (methods)。

使用Store

<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()

//1.使用storeToRefs()解构赋值保持响应性
const { count, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store


//2.直接使用store访问
store.count++
</script>

store 是一个用 reactive 包装的对象
直接使用const { count, doubleCount } = store解构出来的属性(stetegetters)是非响应式的,需要使用storeToRefs()

pinia持久化

pinia 的数据是短时的,只要一刷新页面,数据就会恢复成初始状态,为了避免这个问题,可以对其采用持久化保存方法。使用 pinia-plugin-persistedstate插件

安装

# 安装插件
pnpm add pinia-plugin-persistedstate

引入插件

main.js

//引入插件
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

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

使用插件

方法1:默认保存

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

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('user',()=>{
    const name = ref("")
},
{
 	persist:true
})

方法2:设置key、指定保存内容

主动设置 key 名,使用paths指定哪些数据保存

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('user',()=>{
    const name = ref("")
    const age = ref("")
},
{
 	persist:{
        key:"info"
        storage: localStorage,
        paths: ['name']
 	}
})
//会保存成info:{}的形式

方式3:对不同数据设置不同的本地存储方式

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('user',()=>{
    const name = ref("")
    const age = ref("")
},
{
 	persist:[
         { storage: sessionStorage, paths: ['name'] },
      	 { storage: localStorage, paths: ['age'] },
        ],
 	]
})

进阶用法getItem/setItem

import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useUserStore = defineStore('user',()=>{
    const name = ref("")
    const age = ref("")
    },
 {
    persist:{
        key:"xh_user",
        paths:['name'],
        storage:{
            setItem(key,value) {
                // 使用uni-app的本地缓存方法保存
                uni.setStorageSync(key,value)
            },
            getItem(key) {
                return uni.getStorageSync(key)
            }
        }
    }
})