Vue3 使用Pinia狀態管理


安裝

npm install pinia --save

使用

創建store文件夾

建 src/store 目錄並在其下面創建 index.ts,導出 store

// src/store/index.ts
import { createPinia } from 'pinia'

const store = createPinia()

export default store

在 main.ts 中引入並使用

// src/main.ts

import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

const app = createApp(App)
app.use(store)

創建login.ts文件

建 src/store 目錄並在其下面創建 module/login.ts文件,用來單獨管理各個模塊

// src/store/module/login.ts
import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useLoginStoreSetup = defineStore('useLoginStoreSetup', {
  // Composition API寫法
  // const count = ref<number>(0)
  // const getCount = () => {
  //   return count.value * 2
  // }
  // const incurment = () => {
  //   count.value++
  // }

  // return {
  //   count,
  //   getCount,
  //   incurment
  // }

  // options API寫法
  state: () => ({
    count: 0,
	sum: 0
  }),
  getters: {
    dobule: (state) => state.count
  },
  actions: {
    incurment() {
      this.count++
	  this.sum++
    },
  }
})

獲取store

直接解構會失去響應式: 但是可以通過以下兩種方式獲取
方式1: 通過計算屬性獲取
方式2: 通過pinia 內置方法storeToRefs()

// login.vue
<template>
  <div class="layout-wrap login-wrap">
    <el-button @click="handleBtn">獲取</el-button>
    <div>pinia的state: count會失去響應 = {{ count }}</div>
    <div>pinia的state: sum通過storeToRefs獲取不會失去響應 = {{ sum }}</div>
    <div>pinia的getters: dobule = {{ dobule }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useLoginStoreSetup } from '@/store/module/login'
export default defineComponent({
  setup() {
    const store = useLoginStoreSetup()
    const { incurment, count } = store // 直接解構會使count失去響應式
 // const count = computed(() => store.count) 方式1: 可以通過計算屬性
    const { dobule, sum } = storeToRefs(store) // 方式2: 通過storeToRefs解構sum不會失去響應
    const handleBtn = () => {
      incurment()
    }
    return {
      handleBtn,
      count,
      sum,
      dobule
    }
  }
})
</script>

image

數據持久化

npm i pinia-plugin-persist --save

引入插件

// src/store/index.ts
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist' //+

const store = createPinia() //+
store.use(piniaPluginPersist)

export default store

默認配置

數據默認存在 sessionStorage 里,
並且會以 store 的 id 作為 key。

// src/store/module/login.ts
export const useLoginStoreSetup = defineStore('useLoginStoreSetup', {
  // options API寫法
  state: () => ({
    count: 0,
    token: '',
    userInfo: {}
  }),

  // 開啟數據緩存
  persist: {
    enabled: true
  }
})

image

自定義key

自定義 存儲 key 值,
並將存放位置由 sessionStorage 改為 localStorage。
這里默認緩存state里所有的值

// src/store/module/login.ts
export const useLoginStoreSetup = defineStore('useLoginStoreSetup', {
  // options API寫法
  state: () => ({
    count: 0,
    token: '',
    userInfo: {}
  }),

  // 開啟數據緩存
	persist: {
	  enabled: true,
	  strategies: [
		{
		  key: 'my_user',
		  storage: localStorage,
		}
	  ]
	}
})

image

持久化部分 state

默認所有 state 都會進行緩存
可以通過 paths 指定要持久化的字段,其他的則不會進行持久化

// src/store/module/login.ts
export const useLoginStoreSetup = defineStore('useLoginStoreSetup', {
  // options API寫法
  state: () => ({
    count: 0,
    token: '',
    userInfo: {}
  }),

  // 開啟數據緩存
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ['userInfo', 'token']
      }
    ]
  }
})

上面我們只持久化 name 和 age,並將其改為localStorage,
gender 不會被持久化,如果其狀態發送更改,頁面刷新時將會丟失,重新回到初始狀態,
而 name 和 age 則不會。
image


免責聲明!

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



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