Vuex的理解和應用

1.Vuex概念

  • Vuex 是一個專爲 Vue.js 應用程序開發的狀態管理模式。
  • 通俗的講,Vue組件中有各種data變量,它就是一個狀態,當應用程序足夠龐大時,如果將這些狀態集中管理就會非常方便,於是Vuex便應運而生。

2. Vuex五大核心

  • State(必須)
    • State是Vuex中唯一的數據源。在Vuex中定義,可以全局使用,一般在computed計算屬性中獲取,在頁面中渲染。
    • 定義:
        // store.js
        store: {
            count: 2
        }
    
    • 獲取
    // 方法1:正常獲取
    computed: {
        count () {
            return this.$store.state.count;
        }
    }
    // 方法2: mapState輔助函數
    import { mapState } from 'vuex'
    computed: mapSate({
        count: state=>state.count,    // 箭頭函數
        count: 'count',             // 字符串傳參
        count (state) {            //  使用常規函數
            return state.count;
        }
    })
    computed: mapState(['count'])    // 也可以傳遞字符串數組
    // 方法3:mapState對象展開式
    import { mapState } from 'vuex'
    computed: {
        ...mapState({
            count: 'count'
        })
    }
    
  • Mutations(必須)
    • 更改Store中狀態的唯一方法是提交Mutaion。
    • 定義:
        mutations: {
            increment (state, n) {
                state.count += n;
            }
        }
    
    • 提交
        // 方法一:直接提交
        this.$store.commit('increment', 10);
        // 方法二:使用mapState引入
        import { mapMutations } from 'vuex'
        methods: {
            ...mapMutations([
                'increment', 'add'
            ])
        }
        ...mapMutations({
            'add': 'increment'        //  將 `this.add()` 映射爲 `this.$store.commit('increment')`
        })
    
  • Getters(非必須)
    • 通過Getters可以派生出新的狀態。
    • 通俗的講,Getters和State在Vuex中扮演着類似的功能,都是狀態的集合。假如某一個狀態本身被很多組件使用,但是有的地方又要改變這個數據的形式,這是就要使用Getters,比如購物車中的數量(當大於100時顯示99+)。Getters在組件中的獲取方式和State相同。
    • 定義:
        getters: {
            doneTodos: state=>{
                return state.todos.filter(todo => todo.done)
            }
        }
    
    • 獲取:
        // 方法一:同Sate類似
        return this.$store.getters.doneTodosCount
        // 方法二:同Sate類似
        import { mapGetters } from 'vuex'
        computed: {
            ...mapGetters(['doneTodosCount', 'anotherGetter'])
        }
    
  • Actions(非必須)
    • Action提交的是Mutation,而不是直接變更狀態,Action可以包含任意異步操作。
    • 定義:
        // 方式一
        actions: {
            add (context) {
                context.commit('increment');
            }
        }
        // 方式二
        actions: {
            add ({commit}) {
                commit('increment');
            }
        }
    
    • 分發
        // 方式一:直接分發
        this.$store.dispatch('add');
        // 方式二:在組件中分發
        import { mapActions } from 'vuex'
        methods: {
            ...mapActions(['add', 'other']),
            ...mapActions({
                add: 'increment'  // 將 `this.add()` 映射爲 `this.$store.dispatch('increment')`
            })
        }
    
  • Modules(非必須)
    • 當應用變得非常複雜時,store 對象就有可能變得相當臃腫。爲了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊都有自己的State、Getters、Mutations、Actions。
    • 定義
        const moduleA = {
          state: { ... },
          mutations: { ... },
          actions: { ... },
          getters: { ... }
        }
    
        const moduleB = {
          state: { ... },
          mutations: { ... },
          actions: { ... }
        }
    
        const store = new Vuex.Store({
          modules: {
            a: moduleA,
            b: moduleB
          }
        })
    
        store.state.a // -> moduleA 的狀態
        store.state.b // -> moduleB 的狀態
    

3.功能和應用

  • Vue分析結構圖

輸入圖片說明

  • 項目結構圖

輸入圖片說明

4.優勢和缺點

  • 優勢
    • 集中管理很多狀態
  • 缺點
    • 如果項目不大,代碼會不容易理解,造成結構混亂。

5.應用場景區分

  • 如果項目是列表等靜態數據較多的小應用,那就用不到狀態管理。
  • 如果有少量幾個狀態需要管理的中型應用,可以嘗試使用eventBus,這樣更簡潔。
  • 如果有幾個以上的狀態需要隨時修改和改變狀態,比如購物車數量、登錄狀態等,可以使用Vuex,這樣會更方便。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章