pinia的使用以及持久化存储
vuex和pinia的区别
- pinia没有mutations,只有:state、getters、actions;
- pinia分模块不需要modulles(之前vuex分模块需要modules)
- pinia体积更小(性能更好);
- pinia可以直接修改state数据;
一、安装使用
1、安装下载
npm install pinia
# or
yarn add pinia
2、main.js引入
import {createPinia} from 'pinia' app.use(createPinia())
3、根目录创建store/index.js中写入
import {defineStore} from "pinia"
export const userStore = defineStore("",{
state:()=>{
return{
count:0
}
},
getters:{},
actions:{}
})
4、组件使用
<script setup>
import {userStore} from '../store'
const store = userStore()
</script>
5、修改stroe中的数据
<script setup>
import {storeToRefs} from 'pinia'
const store = userStore()
const {count,name} = storeToRefs(store)
const changeName = () =>{
name.value = 'wanjun'
}
<script >
import {defineStore} from "pinia"
export const userStore = defineStore("storeId",{
state:()=>{
return{
count:0,
name:'z55'
}
},
getters:{
changeNum(){
return this.count +100
}
},
// 支持同步、异步
actions:{
upNum(val){
this.count += val
}
}
})
二、pinia持久化存储
1、安装插件
npm i pinia-plugin-persist --save
2、store/index.js
import {createPinia} from 'pinia'
// 引入pinia持久化存储插件
import piniaPluginPersist from 'pinia-plugin-persist'
const store = createPinia()
//使用插件
store.use(piniaPluginPersist)
export default store
3、在main.js中引入
reateApp} from 'vue'
import App from '@/App.vue'
import {createPinia} from 'pinia'
import store from "@/store/index";
const app = createApp(App)
// 1.createPinia()、2.store有先后顺序
app.use(createPinia())
app.use(store)
app.mount('#app')
store/user.js 本地保存
// 开启数据缓存
persist:{
enabled:true,
strategies:[
{
key:'xiao',
storage:localStorage
}
],
paths:[]
}