1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        新一代狀態(tài)管理工具,Pinia.js 上手指南

        共 7807字,需瀏覽 16分鐘

         ·

        2022-01-16 20:13

        點(diǎn)擊上方 前端瓶子君,關(guān)注公眾號(hào)

        回復(fù)算法,加入前端編程面試算法每日一題群

        前言

        Pinia.js 是新一代的狀態(tài)管理器,由 Vue.js團(tuán)隊(duì)中成員所開發(fā)的,因此也被認(rèn)為是下一代的 Vuex,即 Vuex5.x,在 Vue3.0 的項(xiàng)目中使用也是備受推崇。

        Pinia.js 有如下特點(diǎn):

        • 完整的 typescript 的支持;
        • 足夠輕量,壓縮后的體積只有1.6kb;
        • 去除 mutations,只有 state,getters,actions(這是我最喜歡的一個(gè)特點(diǎn));
        • actions 支持同步和異步;
        • 沒有模塊嵌套,只有 store 的概念,store 之間可以自由使用,更好的代碼分割;
        • 無需手動(dòng)添加 store,store 一旦創(chuàng)建便會(huì)自動(dòng)添加;

        安裝

        npm install pinia --save
        復(fù)制代碼

        創(chuàng)建 Store

        新建 src/store 目錄并在其下面創(chuàng)建 index.ts,導(dǎo)出 store

        // src/store/index.ts

        import { createPinia } from 'pinia'

        const store = createPinia()

        export default store
        復(fù)制代碼

        在 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)
        復(fù)制代碼

        State

        定義State

        在 src/store 下面創(chuàng)建一個(gè)user.ts

        //src/store/user.ts

        import { defineStore } from 'pinia'

        export const useUserStore = defineStore({
          id'user'// id必填,且需要唯一
          state() => {
            return {
              name'張三'
            }
          }
        })

        復(fù)制代碼

        獲取 state

        <template>
          <div>{{ userStore.name }}</div>
        </template>

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

        const userStore = useUserStore()
        </script>
        復(fù)制代碼

        也可以結(jié)合 computed 獲取。

        const name = computed(() => userStore.name)
        復(fù)制代碼

        state 也可以使用解構(gòu),但使用解構(gòu)會(huì)使其失去響應(yīng)式,這時(shí)候可以用 pinia 的 storeToRefs

        import { storeToRefs } from 'pinia'
        const { name } = storeToRefs(userStore)
        復(fù)制代碼

        修改 state

        可以像下面這樣直接修改 state

        userStore.name = '李四'
        復(fù)制代碼

        但一般不建議這么做,建議通過 actions 去修改 state,action 里可以直接通過 this 訪問。

        export const useUserStore = defineStore({
          id'user',
          state() => {
            return {
              name'張三'
            }
          },
          actions: {
            updateName(name) {
              this.name = name
            }
          }
        })
        復(fù)制代碼
        <script lang="ts" setup>
        import { useUserStore } from '@/store/user'

        const userStore = useUserStore()
        userStore.updateName('李四')
        </script>
        復(fù)制代碼

        Getters

        export const useUserStore = defineStore({
         id'user',
         state() => {
           return {
             name'張三'
           }
         },
         getters: {
           fullName(state) => {
             return state.name + '豐'
           }
         }
        })
        復(fù)制代碼
        userStore.fullName // 張三豐
        復(fù)制代碼

        Actions

        異步 action

        action 可以像寫一個(gè)簡(jiǎn)單的函數(shù)一樣支持 async/await 的語法,讓你愉快的應(yīng)付異步處理的場(chǎng)景。

        export const useUserStore = defineStore({
          id'user',
          actions: {
            async login(account, pwd) {
              const { data } = await api.login(account, pwd)
              return data
            }
          }
        })
        復(fù)制代碼

        action 間相互調(diào)用

        action 間的相互調(diào)用,直接用 this 訪問即可。

         export const useUserStore = defineStore({
          id'user',
          actions: {
            async login(account, pwd) {
              const { data } = await api.login(account, pwd)
              this.setData(data) // 調(diào)用另一個(gè) action 的方法
              return data
            },
            setData(data) {
              console.log(data)
            }
          }
        })
        復(fù)制代碼

        在 action 里調(diào)用其他 store 里的 action 也比較簡(jiǎn)單,引入對(duì)應(yīng)的 store 后即可訪問其內(nèi)部的方法了。

        // src/store/user.ts

        import { useAppStore } from './app'
        export const useUserStore = defineStore({
          id'user',
          actions: {
            async login(account, pwd) {
              const { data } = await api.login(account, pwd)
              const appStore = useAppStore()
              appStore.setData(data) // 調(diào)用 app store 里的 action 方法
              return data
            }
          }
        })
        復(fù)制代碼
        // src/store/app.ts

        export const useAppStore = defineStore({
          id'app',
          actions: {
            setData(data) {
              console.log(data)
            }
          }
        })
        復(fù)制代碼

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

        插件 pinia-plugin-persist 可以輔助實(shí)現(xiàn)數(shù)據(jù)持久化功能。

        安裝

        npm i pinia-plugin-persist --save
        復(fù)制代碼

        使用

        // src/store/index.ts

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

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

        export default store
        復(fù)制代碼

        接著在對(duì)應(yīng)的 store 里開啟 persist 即可。

        export const useUserStore = defineStore({
          id'user',

          state() => {
            return {
              name'張三'
            }
          },
          
          // 開啟數(shù)據(jù)緩存
          persist: {
            enabledtrue
          }
        })
        復(fù)制代碼
        image.png

        數(shù)據(jù)默認(rèn)存在 sessionStorage 里,并且會(huì)以 store 的 id 作為 key。

        自定義 key

        你也可以在 strategies 里自定義 key 值,并將存放位置由 sessionStorage 改為 localStorage。

        persist: {
          enabledtrue,
          strategies: [
            {
              key'my_user',
              storage: localStorage,
            }
          ]
        }
        復(fù)制代碼
        image.png

        持久化部分 state

        默認(rèn)所有 state 都會(huì)進(jìn)行緩存,你可以通過 paths 指定要持久化的字段,其他的則不會(huì)進(jìn)行持久化。

        state: () => {
          return {
            name'張三',
            age18,
            gender'男'
          }  
        },

        persist: {
          enabledtrue,
          strategies: [
            {
              storage: localStorage,
              paths: ['name''age']
            }
          ]
        }
        復(fù)制代碼

        上面我們只持久化 name 和 age,并將其改為localStorage, 而 gender 不會(huì)被持久化,如果其狀態(tài)發(fā)送更改,頁面刷新時(shí)將會(huì)丟失,重新回到初始狀態(tài),而 name 和 age 則不會(huì)。

        最后

        以上就是關(guān)于 Pinia.js 用法的一些介紹,Pinia.js 的內(nèi)容還遠(yuǎn)不止這些,更多內(nèi)容及使用有待大家自己探索。Pinia文檔[1]

        感謝

        本次分享到這里就結(jié)束了,感謝您的閱讀,如果本文對(duì)您有什么幫助,別忘了動(dòng)動(dòng)手指點(diǎn)個(gè)贊??。


        來自:小學(xué)生study

        https://juejin.cn/post/7049196967770980389

        最后

        歡迎關(guān)注【前端瓶子君】??ヽ(°▽°)ノ?
        回復(fù)「算法」,加入前端編程源碼算法群,每日一道面試題(工作日),第二天瓶子君都會(huì)很認(rèn)真的解答喲!
        回復(fù)「交流」,吹吹水、聊聊技術(shù)、吐吐槽!
        回復(fù)「閱讀」,每日刷刷高質(zhì)量好文!
        如果這篇文章對(duì)你有幫助,在看」是最大的支持

         》》面試官也在看的算法資料《《
        “在看和轉(zhuǎn)發(fā)”就是最大的支持


        瀏覽 230
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評(píng)論
        圖片
        表情
        推薦
        點(diǎn)贊
        評(píng)論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            欧美大香蕉在线视频 | 黄片a片97大黄片 | 狠狠干天天操 | P站免费版 - 永久免费的福利视频平台 | 嗯啊不要视频 | 欧美性爱999 | A片无遮挡性高爱潮视频播放 | 性爱视频网站 | 宋佳双乳高耸呻吟不止 | 欧美影院二区 |