溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Pinia簡單使用及數(shù)據(jù)持久化怎么實現(xiàn)

發(fā)布時間:2022-05-30 10:23:47 來源:億速云 閱讀:652 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要講解了“Pinia簡單使用及數(shù)據(jù)持久化怎么實現(xiàn)”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Pinia簡單使用及數(shù)據(jù)持久化怎么實現(xiàn)”吧!

基本介紹

Pinia 是 Vue.js 的輕量級狀態(tài)管理庫

  • pinia和vuex4一樣,也是vue官方的狀態(tài)管理工具(作者是 Vue 核心團(tuán)隊成員)

  • pinia相比vuex4,對于vue3的兼容性更好

  • pinia相比vuex4,具備完善的類型推薦

  • pinia同樣支持vue開發(fā)者工具,最新的開發(fā)者工具對vuex4支持不好

pinia核心概念

  • state: 狀態(tài)

  • actions: 修改狀態(tài)(包括同步和異步,pinia中沒有mutations)

  • getters: 計算屬性

基本使用與state

目標(biāo):掌握pinia的使用步驟

(1)安裝

yarn add pinia
# or
npm i pinia

(2)在main.js中掛載pinia

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

import { createPinia } from 'pinia'
const pinia = createPinia()

createApp(App).use(pinia).mount('#app')

(3)新建文件store/counter.js

import { defineStore } from 'pinia'
// 創(chuàng)建store,命名規(guī)則: useXxxxStore
// 參數(shù)1:store的唯一表示
// 參數(shù)2:對象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  getters: {
   
  },
  actions: {
    
  },
})

export default useCounterStore

(4) 在組件中使用

<script setup>
import useCounterStore from './store/counter'

const counter = useCounterStore()
</script>

<template>
  <h2>根組件---{{ counter.count }}</h2>
</template>

<style></style>

actions的使用

目標(biāo):掌握pinia中actions的使用

在pinia中沒有mutations,只有actions,不管是同步還是異步的代碼,都可以在actions中完成。

(1)在actions中提供方法并且修改數(shù)據(jù)

import { defineStore } from 'pinia'
// 1. 創(chuàng)建store
// 參數(shù)1:store的唯一表示
// 參數(shù)2:對象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  actions: {
    increment() {
      this.count++
    },
    incrementAsync() {
      setTimeout(() => {
        this.count++
      }, 1000)
    },
  },
})

export default useCounterStore

(2)在組件中使用

<script setup>
import useCounterStore from './store/counter'

const counter = useCounterStore()
</script>

<template>
  <h2>根組件---{{ counter.count }}</h2>
  <button @click="counter.increment">加1</button>
  <button @click="counter.incrementAsync">異步加1</button>
</template>

getters的使用

pinia中的getters和vuex中的基本是一樣的,也帶有緩存的功能

(1)在getters中提供計算屬性

import { defineStore } from 'pinia'
// 1. 創(chuàng)建store
// 參數(shù)1:store的唯一表示
// 參數(shù)2:對象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  getters: {
    double() {
      return this.count * 2
    },
  },
  actions: {
    increment() {
      this.count++
    },
    incrementAsync() {
      setTimeout(() => {
        this.count++
      }, 1000)
    },
  },
})

export default useCounterStore

(2)在組件中使用

  <h2>根組件---{{ counter.count }}</h2>
  <h4>{{ counter.double }}</h4>

storeToRefs的使用

目標(biāo):掌握storeToRefs的使用

如果直接從pinia中解構(gòu)數(shù)據(jù),會丟失響應(yīng)式, 使用storeToRefs可以保證解構(gòu)出來的數(shù)據(jù)也是響應(yīng)式的

<script setup>
import { storeToRefs } from 'pinia'
import useCounterStore from './store/counter'

const counter = useCounterStore()
// 如果直接從pinia中解構(gòu)數(shù)據(jù),會丟失響應(yīng)式
const { count, double } = counter

// 使用storeToRefs可以保證解構(gòu)出來的數(shù)據(jù)也是響應(yīng)式的
const { count, double } = storeToRefs(counter)
</script>

pinia模塊化

在復(fù)雜項目中,不可能把多個模塊的數(shù)據(jù)都定義到一個store中,一般來說會一個模塊對應(yīng)一個store,最后通過一個根store進(jìn)行整合

(1)新建store/user.js文件

import { defineStore } from 'pinia'

const useUserStore = defineStore('user', {
  state: () => {
    return {
      name: 'zs',
      age: 100,
    }
  },
})

export default useUserStore

(2)新建store/index.js

import useUserStore from './user'
import useCounterStore from './counter'

// 統(tǒng)一導(dǎo)出useStore方法
export default function useStore() {
  return {
    user: useUserStore(),
    counter: useCounterStore(),
  }
}

(3)在組件中使用

<script setup>
import { storeToRefs } from 'pinia'
import useStore from './store'
const { counter } = useStore()

// 使用storeToRefs可以保證解構(gòu)出來的數(shù)據(jù)也是響應(yīng)式的
const { count, double } = storeToRefs(counter)
</script>

pinia數(shù)據(jù)持久化

目標(biāo): 通過 Pinia 插件快速實現(xiàn)持久化存儲。

插件文檔:點擊查看

用法

安裝

yarn add pinia-plugin-persistedstate
or
npm i  pinia-plugin-persistedstate

使用插件 在main.ts中注冊

import { createApp } from "vue";
import App from "./App.vue";
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia();
pinia.use(piniaPluginPersistedstate);
createApp(App).use(pinia);

模塊開啟持久化

const useHomeStore = defineStore("home",{
  // 開啟數(shù)據(jù)持久化
  persist: true
  // ...省略
});

常見疑問

  • 模塊做了持久化后,以后數(shù)據(jù)會不會變,怎么辦?

    • 先讀取本地的數(shù)據(jù),如果新的請求獲取到新數(shù)據(jù),會自動把新數(shù)據(jù)覆蓋掉舊的數(shù)據(jù)。

    • 無需額外處理,插件會自己更新到最新數(shù)據(jù)。

進(jìn)階用法

需求:不想所有數(shù)據(jù)都持久化處理,能不能按需持久化所需數(shù)據(jù),怎么辦?

  • 可以用配置式寫法,按需緩存某些模塊的數(shù)據(jù)。

import { defineStore } from 'pinia'

export const useStore = defineStore('main', s{
  state: () => {
    return {
      someState: 'hello pinia',
      nested: {
        data: 'nested pinia',
      },
    }
  },
  // 所有數(shù)據(jù)持久化
  // persist: true,
  // 持久化存儲插件其他配置
  persist: {
    // 修改存儲中使用的鍵名稱,默認(rèn)為當(dāng)前 Store的 id
    key: 'storekey',
    // 修改為 sessionStorage,默認(rèn)為 localStorage
    storage: window.sessionStorage,
    // 部分持久化狀態(tài)的點符號路徑數(shù)組,[]意味著沒有狀態(tài)被持久化(默認(rèn)為undefined,持久化整個狀態(tài))
    paths: ['nested.data'],
  },
})

總結(jié):相比于vuex,pinia對于typescript的支持性更好,友好的devTools支持,pinia只有1kb,簡化了很多方法的寫法。

感謝各位的閱讀,以上就是“Pinia簡單使用及數(shù)據(jù)持久化怎么實現(xiàn)”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Pinia簡單使用及數(shù)據(jù)持久化怎么實現(xiàn)這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI