欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue3如何用pinia替代vuex

 更新時間:2024年03月09日 09:01:01   作者:sqwu  
這篇文章主要介紹了vue3如何使用pinia替代vuex問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

pinia是vue團(tuán)隊推薦代替vuex的一款輕量級狀態(tài)管理庫。

1. 安裝

npm i pinia --save

2. pinia特點(diǎn)

  • 完整的typescript支持
  • 足夠輕量,壓縮后的體積只有1.6kb
  • 去除mutations,只保留state,getters,actions
  • actions同時支持同步和異步
  • 沒有modules模塊的概念,只有store,store之間可以互相引用,更好的代碼分割

3. 使用

1.初始化store

創(chuàng)建目錄store/index.ts

import { createPinia } from 'pinia'

const store = createPinia()

export default store

2.在main.ts引用store

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

const app = createApp(App)

app.use(store)
app.mount('#app')

3.創(chuàng)建store

根據(jù)功能模塊在store下創(chuàng)建ts文件,維護(hù)各個功能的數(shù)據(jù),如用戶模塊user.ts,維護(hù)兩個字段:userInfo和token,通過actions里面的方法修改userInfo和token的內(nèi)容

import { defineStore } from 'pinia'

interface UserInfo {
  name?: string
  age?: number
}

// 第一個參數(shù)是id,id必填,且需要保證值唯一
export const useUserStore = defineStore('user', {
  state: (): {
    userInfo: UserInfo
    token: string
  } => {
    return {
      userInfo: {},
      token: ''
    }
  },
  getters: {
    newName: state => state.userInfo.name + '牛'
  },
  actions: {
    updateUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo
    },
    updateToken(token: string) {
      this.token = token
    }
  }
})

4.讀取數(shù)據(jù)

引入要讀取的store

<script setup lang="ts">
import { useUserStore } from '../../store/user'

const userStore = useUserStore()

// 讀取state中的數(shù)據(jù)
const userInfo: ComputedRef<{
  name?: string
  age?: number
}> = computed(() => userStore.userInfo)

// 讀取getter中的數(shù)據(jù)
const newName = userStore.newName
</script>

5.修改數(shù)據(jù)

<script lang="ts" setup>
import { useUserStore } from '../../store/user'

const userStore = useUserStore()

function handleLogin() {
  userStore.updateUserInfo({ name: '李二' })
}
</script>

6.store的相互引用

不同store之間引用,舉個??:創(chuàng)建user2.ts,引用user.ts的數(shù)據(jù)

import { defineStore } from 'pinia'
import { useUserStore } from './user'

export const useUser2Store = defineStore('user2', {
  state: (): {
    sex: string
  } => {
    return {
      sex: '0'
    }
  },
  actions: {
    sayInfo(sex: string) {
      this.sex = sex
  
      // 引用其他store
      const userStore = useUserStore()
      console.log(
        `我叫${userStore.newName}, 我是個小${
          this.sex === '0' ? '姑娘' : '伙子'
        }`
      )
    }
  }
})

在組件中使用user2模塊

<script lang="ts" setup>
import { useUser2Store } from '../../store/user2'

const user2Store = useUser2Store()

setTimeout(() => {
  user2Store.sayInfo('1')
}, 3000) // 3s后輸出----》 我叫李二牛, 我是個小伙子
</script>

7.devtools

在devtools中可以看到,pinia會自動根據(jù)文件區(qū)分模塊!

[image.png](https://img-blog.csdnimg.cn/img_convert/cc84658cff008f5a4f12cd055b0d3e63.png#clientId=ub02bfd39-d58d-4&crop=0&crop=0&crop=1&crop=1&from=paste&height=334&id=ua2094b26&margin=[object Object]&name=image.png&originHeight=334&originWidth=854&originalType=binary&ratio=1&rotation=0&showTitle=false&size=28525&status=done&style=none&taskId=u68d66ff1-1cbd-4188-883d-42b4edf1940&title=&width=854

4.數(shù)據(jù)持久化

開啟持久化可以在頁面刷新的時候,幫我們把數(shù)據(jù)緩存下來,不被清空。

1.安裝插件

npm i pinia-plugin-persist --save

2.引用插件

在store/index.ts引入插件,并且use

import { createPinia } from 'pinia'
import piniaPluginpersist from 'pinia-plugin-persist'

const store = createPinia()

// 使用持久化插件
store.use(piniaPluginpersist)

export default store

3.在store模塊中啟用持久化

(1) 啟用

在user.ts中啟用:添加persist配置項

import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {
  state: (): {
    userInfo: UserInfo
    token: string
  } => ({
    userInfo: {},
    token: ''
  }),
  getters: { ... },
  actions: { ... },
    
  // 開始數(shù)據(jù)持久化
  persist: {
    enabled: true
  }
})

數(shù)據(jù)會默認(rèn)存儲到sessionStorage,可以在控制臺看到。

(2) 修改key & 存儲位置

默認(rèn)存儲到sessionStorage的key值就是store模塊id值??梢酝ㄟ^strategies修改key值和存儲位置,如:

將key值改為_user,存儲位置改為localStorage(注意之前緩存在sessionStorage中的數(shù)據(jù)還在,可以手動清除一下sessionStorage.clear())

persist: {
    enabled: true,
    strategies: [{
      key: '_user',
      storage: localStorage
    }]
  }

在控制臺打印localStorage

(3) 自定義要持久化的字段

默認(rèn)會將store中的所有字段都緩存,可以通過paths指定要緩存的字段。

如:我只要緩存userInfo

  persist: {
    enabled: true,
    strategies: [{
      key: '_user',
      storage: localStorage,
      paths: ['userInfo']
    }]
  }

控制臺打印,可以看到token字段沒有了!

總結(jié)

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論