安装Pinia 状态管理库
npm install pinia
在main.js中引入
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
store/figure.js
import {defineStore} from 'pinia';
export const figure= defineStore('figure',{
state:()=>{
return {
names : 'ying',
age : 18
}
},
getters:{
changeMoney(){
return this.money + 500
}
},
actions:{
addMoney(value){
this.money += value
}
}
})
pinia分模块
在store文件夹下创建js文件,每个js文件就是一个模块,如:
// user.js
import {defineStore} from 'pinia';
export const user = defineStore('user',{
state:()=>{
return {
names : 'fan',
age : 18 ,
}
},
getters:{
},
actions:{
}
})
pinia简单用法
<template>
<button @click="changes">修改</button>
<div>姓名:{{ names }}</div>
<div>年龄:{{ age }}</div>
<div>money:{{ changeMoney }}</div>
<button @click="btn">actions</button>
<button @click="reset">重置</button>
</template>
<script setup>
// 用那个模块引入那个模块
import { figure} from '@/store/figure';
import {storeToRefs} from 'pinia';
const store = figure();
let {names, age, changeMoney} = storeToRefs(store)
const changeAge = ()=>{
// 第一种修改方法
// age.value +=1
// 第二种修改方法 可以不用 let { names ...} = storeToRefs(store)
// 直接 {{ state.age }}
store.$patch(state=>{
state.age+=1
state.money += 500
})
}
// 触发actions
const btn = ()=>{
store.addMoney(500)
}
// 重置
const reset = ()=>{
store.$reset()
}
</script>
pinia持久化存储
npm install pinia-plugin-persist
main.js
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist'
const pinia = createPinia()
const app = createApp(App)
pinia.use(piniaPersist)
app.use(pinia).mount('#app')
xxx.js文件中
actions:{
},
persist:{
enabled: true,
// 默认是sessionStorage 即关闭标签页就会清除缓存
strategies: [{
key:'cs',
storage: localStorage
}]
}