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 上手指南

        共 4419字,需瀏覽 9分鐘

         ·

        2022-02-26 20:08

        大廠技術(shù)??高級前端??Node進(jìn)階

        點擊上方?程序員成長指北,關(guān)注公眾號

        回復(fù)1,加入高級Node交流群


        前言

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

        Pinia.js 有如下特點:

        • 完整的 typescript 的支持;
        • 足夠輕量,壓縮后的體積只有1.6kb;
        • 去除 mutations,只有 state,getters,actions(這是我最喜歡的一個特點);
        • actions 支持同步和異步;
        • 沒有模塊嵌套,只有 store 的概念,store 之間可以自由使用,更好的代碼分割;
        • 無需手動添加 store,store 一旦創(chuà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)建一個user.ts

        //src/store/user.ts

        import?{?defineStore?}?from?'pinia'

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

        復(fù)制代碼

        獲取 state