内容一切从简,看完就会用。
概念【可跳过】
State:存储状态(共享数据)的地方,类似于Vuex中的store,但更加灵活---单纯存数据的地方。
Getters:从存储的状态(共享数据)中派生数据(类似计算属性)---数据改变后想做的操作。
Actions:用于改变状态(共享数据)的方法---数据的操作方法都放在这里。
Plugins:可选的扩展点,用于添加额外的功能。
State、Getters和Actions,我们可以将它们等价于组件中的“数据”、“计算属性”和“方法”。
安装
npm install pinia
yarn add pinia
main.js挂载
import {createPinia} from 'pinia'
const pinia = createPinia()
app.use(pinia)
创建store/counter.js
import { defineStore } from 'pinia'
import {ref} from 'vue'
export const useCounterStore = defineStore('counter', () => {
const counter = ref(1)
const increment=(val)=>{
val?counter.value+=val:counter.value++
}
return { counter, increment }
})
读取数据
<template>
<div>
<p>原始的值:{{ counter }}</p>
</div>
</template>
<script setup>
import { useCounterStore } from '../store/counter';
import {storeToRefs} from 'pinia';
let counterStore=useCounterStore();
const {counter}=storeToRefs(counterStore);
//js读取需要.value
console.log(counter.value);
</script>
修改数据
<template>
<div>
<p>原始的值:{{ counter }}</p>
<button @click="incrementFn">包一下</button>
<button @click="counterStore.increment()">直接用</button>
</div>
</template>
<script setup>
const incrementFn=()=>{
counterStore.increment()
}
</script>
pinia的API
监听变化 $subscribe
counterStore.$subscribe((val, state) => {
console.log(state,'state');
console.log(state.counter,'state.counter');
});
恢复初始值 $reset
<button @click="reset">恢复初始值</button>
const reset=()=>{
countStore.$reset()
}
恢复初始值API的问题解决方案
//main.js添加该内容
pinia.use(({store})=>{
const initialState = JSON.parse(JSON.stringify(store.$state));
store.$reset = ()=>{
store.$state = JSON.parse(JSON.stringify(initialState));
}
});
修改多个值 $patch
※ 其他的不会发生变化
const patchFn=()=>{
counterStore.$patch({
counter: counterStore.counter + 1,
user: 'Abalam'+(counterStore.counter+1),
})
}
整体修改 $state
※ 目前使用下来类似 $patch,功能类似写法不同
const stateFn=()=>{
counterStore.$state={
counter: counterStore.counter + 1,
user: 'Abalam'+(counterStore.counter+1),
}
}
pinia的持久化
安装
npm install pinia-plugin-persistedstate
main引入
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
store中配置
persist: {
// 持久化
enabled: true,
strategies: [
// 持久化策略
{
key: 'countStore', // 修改存在缓存中的key值
storage: localStorage, // 修改存储方式为localStorage
paths:['count'] // 只持久化count,此时刷新页面count数据会被保留,其他state将会重置
},
],
},