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)