pinia简单使用及持久化
pinia使用
安装
npm i pinia --save
新建store目录,创建index.ts
import { createPinia } from "pinia"; const store = createPinia(); export default store;
main.ts中使用store
import { createApp } from 'vue' import store from './store' const app = createApp(App) app.use(store) app.mount('#app')
新建user.ts
import { defineStore } from "pinia"; export const useUserStore = defineStore({ id:'user', state() { return { name: '', age: null, } } })
在vue页面中使用
template中
<template> <p>姓名:{{name}}</p> <p>年龄:{{age}}</p> </template>
script中
import { storeToRefs } from 'pinia' import { useUserStore } from '../../store/module/user'; const store = useUserStore(); const { name, age } = storeToRefs(store)
修改store中的值
import { useCurrentMenuStore } from '../../store/module/menu'; const store = useCurrentMenuStore(); const changeUserInfo = () => { store.name = '修改的name'; store.age = '修改的age' }
pinia持久化
安装
npm i pinia-plugin-persist --save
修改store文件夹下的index.ts
import { createPinia } from "pinia"; import piniaPluginPersist from 'pinia-plugin-persist' const store = createPinia(); store.use(piniaPluginPersist); export default store;
修改需要持久化的store模块:添加persist,storage默认是sessionStorage
import { defineStore } from "pinia"; export const useUserStore = defineStore({ id:'user', state() { return { name: '', age: null, } }, persist: { enabled: true, strategies: [ { key: 'user', storage: localStorage, } ] } })
页面中使用pinia数据,pinia数据更新时,页面数据不更新
使用时用计算属性computed
import useCommonStore from '@/stores'; const currentPath = computed (()=> useCommonStore().currentPath)