Pinia 是一个用于 Vue 的状态管理库,类似 Vuex, 是 Vue 的另一种状态管理方案
Pinia 支持 Vue2 和 Vue3
安装 Pinia
安装 pinia 和持久化插件pinia-plugin-persistedstate
yarn add pinia
yarn add pinia-plugin-persistedstate
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app.mount('#app')
js
src目录下创建stores文件夹
创建文件counter.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => {
return {
// 所有这些属性都将自动推断其类型
count: 0,
name: 'Eduardo',
isAdmin: true,
}
},
getters: {
doubleCount: (state: any) => state.count * 2
},
actions: {
increment() {
this.count++
},
randomizeCounter() {
this.count = Math.round(100 * Math.random())
},
},
persist:{
// 存储的 key, 默认是 defineStore 的第一个参数
// key: "A",
// 存储路径
storage: localStorage,
// 指定内容
paths: ["count","name"],
}
})
使用
<script setup lang="ts">
import { useCounterStore } from './../stores/counter'
const counter = useCounterStore()
function resetStore(){
counter.$reset()
}
</script>
<template>
<p>this is {{ counter.count }}-- {{ counter.doubleCount }}</p>
<input type="text" v-model="counter.count" />
<button @click="counter.increment">increment</button>
<button @click="resetStore">resetStore</button>
</template>
ts
代码 :https://gitee.com/paipaicui/PiniaTest