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)

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM