最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue3如何用pinia替代vuex

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

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

1. 安裝

npm i pinia --save

2. pinia特點(diǎn)

  • 完整的typescript支持
  • 足夠輕量,壓縮后的體積只有1.6kb
  • 去除mutations,只保留state,getters,actions
  • actions同時(shí)支持同步和異步
  • 沒(méi)有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ù)各個(gè)功能的數(shù)據(jù),如用戶模塊user.ts,維護(hù)兩個(gè)字段:userInfo和token,通過(guò)actions里面的方法修改userInfo和token的內(nèi)容

import { defineStore } from 'pinia'

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

// 第一個(gè)參數(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之間引用,舉個(gè)??:創(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}, 我是個(gè)小${
          this.sex === '0' ? '姑娘' : '伙子'
        }`
      )
    }
  }
})

在組件中使用user2模塊

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

const user2Store = useUser2Store()

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

7.devtools

在devtools中可以看到,pinia會(huì)自動(dòng)根據(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ù)持久化

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

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配置項(xiàng)

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

數(shù)據(jù)會(huì)默認(rèn)存儲(chǔ)到sessionStorage,可以在控制臺(tái)看到。

(2) 修改key & 存儲(chǔ)位置

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

將key值改為_(kāi)user,存儲(chǔ)位置改為localStorage(注意之前緩存在sessionStorage中的數(shù)據(jù)還在,可以手動(dòng)清除一下sessionStorage.clear())

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

在控制臺(tái)打印localStorage

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

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

如:我只要緩存userInfo

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

控制臺(tái)打印,可以看到token字段沒(méi)有了!

總結(jié)

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

相關(guān)文章

  • 利用Vue與D3.js創(chuàng)建交互式數(shù)據(jù)可視化

    利用Vue與D3.js創(chuàng)建交互式數(shù)據(jù)可視化

    在現(xiàn)代Web開(kāi)發(fā)中,數(shù)據(jù)可視化是一個(gè)引人矚目的熱點(diǎn)領(lǐng)域,從簡(jiǎn)單的圖表到復(fù)雜的交互式儀表盤,數(shù)據(jù)可視化能夠幫助用戶更好地理解數(shù)據(jù),而Vue與D3.js的結(jié)合則為我們提供了構(gòu)建這些可視化效果的強(qiáng)大工具,本文將向您展示如何利用Vue與D3.js創(chuàng)建一個(gè)基本的交互式數(shù)據(jù)可視化項(xiàng)目
    2025-02-02
  • .netcore+vue 實(shí)現(xiàn)壓縮文件下載功能

    .netcore+vue 實(shí)現(xiàn)壓縮文件下載功能

    這篇文章主要介紹了.netcore+vue 實(shí)現(xiàn)壓縮文件下載功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-09-09
  • 從源碼角度帶你深入理解Vue依賴收集的核心

    從源碼角度帶你深入理解Vue依賴收集的核心

    在?Vue?的響應(yīng)式系統(tǒng)中,依賴收集是貫穿整個(gè)數(shù)據(jù)驅(qū)動(dòng)視圖的核心環(huán)節(jié),本文將從?Vue?2?的源碼出發(fā),層層拆解依賴收集的完整流程,帶你從?“使用層”?走向?“原理層”,真正理解?Vue?響應(yīng)式的底層邏輯
    2026-03-03
  • VUE 實(shí)現(xiàn)element upload上傳圖片到阿里云

    VUE 實(shí)現(xiàn)element upload上傳圖片到阿里云

    這篇文章主要介紹了VUE 實(shí)現(xiàn)element upload上傳圖片到阿里云,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-08-08
  • 淺談vue項(xiàng)目打包優(yōu)化策略

    淺談vue項(xiàng)目打包優(yōu)化策略

    這篇文章主要介紹了淺談vue項(xiàng)目打包優(yōu)化策略,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-09-09
  • Vue中@click事件的常見(jiàn)修飾符用法總結(jié)

    Vue中@click事件的常見(jiàn)修飾符用法總結(jié)

    這篇文章主要給大家介紹了關(guān)于Vue中@click事件的常見(jiàn)修飾符用法的相關(guān)資料,@click事件修飾符是在Vue組件中用來(lái)修改@click事件行為的特殊標(biāo)記,需要的朋友可以參考下
    2023-10-10
  • vue恢復(fù)初始數(shù)據(jù)this.$data,this.$options.data()解析

    vue恢復(fù)初始數(shù)據(jù)this.$data,this.$options.data()解析

    這篇文章主要介紹了vue恢復(fù)初始數(shù)據(jù)this.$data,this.$options.data()解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • 淺談vue的iview列表table render函數(shù)設(shè)置DOM屬性值的方法

    淺談vue的iview列表table render函數(shù)設(shè)置DOM屬性值的方法

    下面小編就為大家?guī)?lái)一篇淺談vue的iview列表table render函數(shù)設(shè)置DOM屬性值的方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-09-09
  • vue實(shí)現(xiàn)固定位置顯示功能

    vue實(shí)現(xiàn)固定位置顯示功能

    這篇文章主要介紹了vue實(shí)現(xiàn)固定位置顯示功能,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2019-05-05
  • 在vscode 中設(shè)置 vue模板內(nèi)容的方法

    在vscode 中設(shè)置 vue模板內(nèi)容的方法

    這篇文章主要介紹了在vscode 中設(shè)置 vue模板內(nèi)容的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-09-09

最新評(píng)論

镇赉县| 手机| 花莲县| 沧源| 彭泽县| 鄂州市| 凌源市| 台湾省| 乌兰察布市| 游戏| 陵川县| 韶山市| 灵宝市| 百色市| 库车县| 沙田区| 富民县| 阳春市| 哈尔滨市| 清涧县| 依兰县| 海安县| 临沂市| 故城县| 偏关县| 会东县| 辉南县| 河曲县| 谷城县| 乌鲁木齐市| 南昌市| 碌曲县| 洪洞县| 潞城市| 历史| 英山县| 金门县| 阳新县| 天水市| 汶上县| 德安县|