VueX 基本使用(vue狀態管理)及簡單小實例


1、安裝vuex依賴包

npm install vuex --save

2、導入vuex包

import Vuex from 'vuex'
Vue.use(Vuex)

3、創建 store 對象

export default new Vuex.Store({
  // state 中存放的就是全局共享的數據
  state: {
    count: 0
  }
})

4、將 store 對象掛載到 vue 實例中

new Vue({
  el: '#app',
  render: h => h(App),
  router,
  // 將創建的共享數據對象,掛載到 Vue 實例中
  // 所有的組件,就可以直接用 store 中獲取全局的數據了
  store
})

VueX:狀態管理

Vuex 是一個專為 Vue.js 應用程序開發的狀態管理模式。它采用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。

核心模塊:State、Getters、Mutations、Actions、Module

(1)、State:

State 提供唯一的公告數據源,所有共享的數據都要統一放到 Store 的 State 中進行存儲。我們需要保存的數據就保存在這里,可以在頁面通過 this.$store.state來獲取我們定義的數據。
// 創建store數據源,提供唯一公共數據
const store = new Vuex.Store({
   state: {
      count: 0
   }
})

組件訪問 Store 中數據的第一種方式:

this.$store.state.全局數據名稱

組件訪問 Store 中數據的第二種方式:

// 1.從 vuex 中按需導入 mapState 函數
import { mapState } from 'vuex'

通過剛才導入的 mapState 函數,將當前組件需要的全局數據,映射為當前組件的 computed 計算屬性:

// 2.將全局數據,映射為當前組件的計算屬性
computed: {
    ...mapState(['count'])
}

(2)、Getters:

Getter相當於vue中的computed計算屬性,不會修改 state 里的源數據,只起到一個包裝器的作用,將 state 里的數據變一種形式然后返回出來。getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變才會被重新計算,這里我們可以通過定義vuex的Getter來獲取,Getters 可以用於監聽、state中的值的變化,返回計算后的結果。

① Getter 可以對 Store 中已有的數據加工處理之后形成新的數據,類似Vue的計算屬性。
② Store 中數據發生變化,Getter 包裝出來的數據也會跟着變化。

定義:

// 定義 Getter
const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    showNum: state => {
      return '當前最新的數量是【'+ state.count +'】'
    }
  }
})

使用 getters 的第一種方式:

this.$store.getters.名稱

使用 getters 的第二種方式:

import { mapGetters } from 'vuex'

computed: {
  ...mapGetters(['showNum'])
}

(3)、Mutations:

更改 Vuex 的 store 中的狀態的唯一方法是提交 mutation,只有 mutation 里的函數才有權利去修改 state 中的數據。Vuex 中的 mutation 非常類似於事件:每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。但是,mutation只允許同步函數,不能寫異步的代碼

①只能通過 mutation 變更 Store 數據,不可以直接操作 Store 中的數據。
②通過這種方式雖然操作起來稍微繁瑣一些,但是可以集中監控所有數據的變化。

定義:

// 定義 Mutation
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    add (state) {
      // 變更狀態
      state.count++
    }
  }
})

第一種觸發方式:

// 觸發 mutation
methods: {
    handleAdd () {
      // 觸發 mutations 的第一種方式
      this.$store.commit('add')
    }
}

還可以在觸發 mutations 時傳遞參數:

// 定義 Mutation
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    addN (state, step) {
      // 變更狀態
      state.count += step
    }
  }
})

第一種觸發方式:

// 觸發 mutation
methods: {
    handleAdd () {
      this.$store.commit('addN', 3)
    }
}

觸發 mutations 的第二種方式:

// 1.從 vuex 中按需導入 mapMutations 函數
import { mapMutations } from 'vuex'

通過剛才導入的 mapMutations 函數,將需要的 mutations 函數,映射為當前組件的 methods 方法:

// 2.將指定的 mutations 函數,映射為當前組件的methods 函數:
methods: {
   ...mapMutations({'add', 'addN'})
}

注意:不要在 mutations 函數中,執行異步操作。所以就需要用到了 Action 用於處理異步任務。 

(4)、Actions:

官方並不建議我們直接去修改store里面的值,而是讓我們去提交一個actions,在actions中提交mutation再去修改狀態值。可以異步操作。

Action 類似於 mutation,不同在於:

  • Action 提交的是 mutation,而不是直接變更狀態。
  • Action 可以包含任意異步操作。

定義:

// 定義 Action
const store = new Vuex.Store({
  // ...省略其他代碼
  mutations: {
    add (state) {
      state.count++
    }
  },
  actions: {
    addAsync (context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000)
    }
  }
})

第一種方式觸發:

// 觸發 Action
methods: {
  handleAdd () {
      // 觸發 actions 的第一種方式
      this.$store.dispatch('addAsync')
  }
}

注意:在 actions 中,不能直接修改 state 中的數據,必須通過 context.commit() 觸發某個 mutations 的函數才行。

觸發 actions 異步任務時攜帶參數: 

定義:

// 定義 Action
const store = new Vuex.Store({
  // ...省略其他代碼
  mutations: {
    addN (state, step) {
      state.count += step
    },
  },
  actions: {
    addNAsync (context, step) {
      setTimeout(() => {
        context.commit('addN', step)
      }, 1000)
    }
  }
})

觸發:

// 觸發 Action
methods: {
  handleAdd () {
      // 在調用 dispatch 函數,觸發 actions 時攜帶參數
      this.$store.dispatch('addNAsync', 5)
  }
}

觸發 actions 的第二種方式: 

// 1.從 vuex 中按需導入 mapActions 函數
import { mapActions } from 'vuex'

通過剛才導入的 mapActions 函數,將需要的 actions 函數,映射為當前組件的 methods 方法:

// 2.將指定的 actions 函數,映射為當前組件的 methods 函數
methods: {
  ...mapActions(['addAsync', 'addNAsync'])
}

 

 

(5)、Module

Vuex 允許我們將store 分割成模塊(module)。每個模塊擁有自己的 state、mutation、action、getter、甚至是嵌套子模塊——從上至下進行同樣方式的分割。

簡要介紹各模塊在流程中的功能:

  • Vue Components:Vue 組件。HTML 頁面上,負責接收用戶操作等交互行為,執行 dispatch 方法觸發對應 action 進行回應。
  • dispatch:操作行為觸發方法,是唯一能執行 action 的方法。
  • actions:操作行為處理模塊,由組件中的$store.dispatch('action 名稱', data1)來觸發。然后由 commit()來觸發 mutation 的調用 , 間接更新 state。負責處理 Vue Components 接收到的所有交互行為。包含同步/異步操作,支持多個同名方法,按照注冊的順序依次觸發。向后台 API 請求的操作就在這個模塊中進行,包括觸發其他 action 以及提交 mutation 的操作。該模塊提供了 Promise 的封裝,以支持 action 的鏈式觸發。
  • commit:狀態改變提交操作方法。對 mutation 進行提交,是唯一能執行 mutation 的方法。
  • mutations:狀態改變操作方法,由 actions 中的commit('mutation 名稱')來觸發。是 Vuex 修改 state 的唯一推薦方法。該方法只能進行同步操作,且方法名只能全局唯一。操作之中會有一些 hook 暴露出來,以進行 state 的監控等。
  • state:頁面狀態管理容器對象。集中存儲 Vue components 中 data 對象的零散數據,全局唯一,以進行統一的狀態管理。頁面顯示所需的數據從該對象中進行讀取,利用 Vue 的細粒度數據響應機制來進行高效的狀態更新。
  • getters:state 對象讀取方法。圖中沒有單獨列出該模塊,應該被包含在了 render 中,Vue Components 通過該方法讀取全局 state 對象。

下面寫個簡單的小實例,方便大家理解VueX:

1、首先在store/index.js里定義state:

state: {
    Count: 0 //數值
},

2、新建一個test.vue文件:

<template>
<div>
    <h3>Count的值:{{this.$store.state.Count}}</h3>
</div>
</template>

這時候運行,頁面上就得到了這個count值為0。

3、在store/index.js里通過getters新建getStateCount方法接收一個參數state,這個參數就是我們用來保存數據的那個對象Count;

getters: {
    getStateCount(state) {
      return state.Count + 1; //返回Count值
    }
}

4、修改test.vue文件

<template>
<div>
    <h3>Count的值:{{this.$store.state.Count}}</h3>
    <h3>從Getters獲取計算后的值:{{this.$store.getters.getStateCount}}</h3>
</div>
</template>

這時在頁面顯示:

5、在頁面下面添加2個按鈕,分別可以增加1、減少1:

修改test.vue頁面:

<template>
<div>
    <h3>Count的值:{{this.$store.state.Count}}</h3>
    <h3>從Getters獲取計算后的值:{{this.$store.getters.getStateCount}}</h3>
    <div>
        <button @click="addCount">+</button>
        <button @click="delCount">-</button>
    </div>
</div>
</template>

<script>
export default {
    methods: {
         addCount:function(){
            this.$store.commit("changAdd");
        },
        delCount:function(){
            this.$store.commit("changDel");
        },
    }
}
</script>

6、因為修改store中的值唯一的方法就是提交mutation來修改,所以在store/index.js里添加mutations,在mutations中定義兩個函數,用來對count加1和減1

mutations: {
    changAdd(state) {
       state.Count = state.Count + 1;
    },
    changDel(state) {
       state.Count = state.Count - 1;
    }
},

這時可以在頁面上點擊+、- 按鈕操作數據:

小bug:Count到0的時候點擊-還可以減1為-1,所以修改下代碼:

changDel(state) {
      if (state.Count == 0) return;
      state.Count = state.Count - 1;
}

OK,現在可以完美實現功能。

但是,官方並不建議我們這樣直接去修改store里面的值,而是讓我們去提交一個actions,在actions中提交mutation再去修改狀態值,接下來我們修改store/index.js文件

7、先定義actions提交mutation的函數:

actions: {
    changAddCount(content) {
       content.commit("changAdd");
    },
    changDelCount(content) {
       content.commit("changDel");
    }
}

8、然后我們去修改test.vue文件:

methods: {
      addCount:function(){
           //this.$store.commit("changAdd");
           this.$store.dispatch("changAddCount")
      },
      delCount:function(){
           //this.$store.commit("changDel");
           this.$store.dispatch("changDelCount")
      },
}

這里我們把commit提交mutations修改為使用dispatch來提交actions;現在我們點擊頁面,效果是一樣的。

好了,我們這里已經實現了一個基本的vuex修改狀態值的完整流程。如果我們需要指定加減的數值,那么我們直接傳入dispatch中的第二個參數,然后在actions中的對應函數中接受參數在傳遞給mutations中的函數進行計算:

9、修改mutations和actions:

mutations: {
    changAdd(state) {
       state.Count = state.Count + 1;
    },
    changDel(state, n) {
       if (state.Count == 0) return;
       state.Count = state.Count - n;
    }
},
actions: {
    changAddCount(content) {
       content.commit("changAdd");
    },
    changDelCount(content, n) {
       content.commit("changDel", n);
    }
}

10、修改test.vue頁面:

methods: {
      addCount:function(){
           //this.$store.commit("changAdd");
           this.$store.dispatch("changAddCount")
      },
      delCount:function(){
           //this.$store.commit("changDel");
           var n = 2;
           this.$store.dispatch("changDelCount", n)
      },
}

這個時候我們再去點擊“ - ”按鈕就會發現不再是減1了,而是減去2了。

這次到1的時候會減為-1,繼續修改:

changDel(state, n) {
    if (state.Count == 0) {
        return;
    } else if (state.Count == 1) {
        state.Count = state.Count - 1;
    } else {
        state.Count = state.Count - n;
    }
}

OK,功能實現了,最終減到0為止。

輔助函數mapState

當一個組件需要獲取多個狀態時候,將這些狀態都聲明為計算屬性會有些重復和冗余。為了解決這個問題,我們可以使用 mapState 輔助函數幫助我們生成計算屬性,讓你少按幾次鍵。

首先要在頁面中構建:

<!-- <h3>Count的值:{{this.$store.state.Count}}</h3> -->
<h3>Count的值:{{Count}}</h3>

<script>
//在單獨構建的版本中輔助函數為 Vuex.mapState
import { mapState } from 'vuex'
//當然也可以一起構建
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'; 
export default {
   computed: mapState({
      // 箭頭函數可使代碼更簡練
      Count: state => state.Count,
   })
}
</script>

對象展開運算符:可以簡化寫法

<!-- <h3>Count的值:{{this.$store.state.Count}}</h3> -->
<h3>Count的值:{{Count}}</h3>

<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex';
export default {
    computed: { //計算屬性
        ...mapState(['Count']), //用...展開運算符把Count展開在資源屬性里
    },
};
</script>

效果當然是一樣的。

mapMutations, mapActions, mapGetters 也一樣可以通過...簡寫:
<h3>Count的值:{{Count}}</h3>
<h3>從Getters獲取計算后的值:{{getStateCount}}</h3>

<script>
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex';
export default {
    computed: { //計算屬性
        ...mapState(['Count']),
        ...mapGetters(['getStateCount']),
    },
    methods: {
        ...mapMutations(['changAdd','changDel']),
        ...mapActions({
            addCount: 'changAddCount',
        }),
        delCount:function(){
            var n = 2;
            this.changDelCount(n);
        },
        ...mapActions({
            changDelCount: "changDelCount",
        }),
    }
};
</script>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM