vuex使用記錄

  • 2020 年 3 月 26 日
  • 筆記

副標題:vuex使用詳解、vue使用全局變數、vue使用 store

這篇部落格主要記錄了 vuex的使用方法,簡單的翻譯了官方文檔加上一點自己的理解。

附上官方文檔的鏈接,想更進一步了解vuex的朋友可以看看:https://vuex.vuejs.org/

有些文章裡面會把 vuex稱作 store,這是因為 vuex里最常用的就是 Store類,綁定到vue環境時也是以 $store 綁定的。我們先簡單了解一下這5個概念。

一、相關概念

按照官方文檔的說法,vuex有5個核心概念,分別是 state、getters、mutations、actions和 modules。

state相當於只讀變數,組件可以訪問 state變數的值,但是不能直接對其進行修改。注意我這裡說的是不能直接進行修改,不是不能修改。想要修改 state里變數的值必須要通過 mutations。

getters就是我們通常所說的 getters,在 getters里可以訪問到所有的 state變數,我們可以方便的用 getters定義一些需要計算的值。

mutations用來修改 state的變數。在 mutations里定義的函數可以修改任意 state變數的值,在組件中通過 store對象的 commit方法調用相關的 mutations函數。

actions的功能和 mutations差不多,唯一的區別就是在 mutations中只支援同步的操作,而在 actions中支援非同步操作(可以在組件中進行鏈式調用,類似 axios)。另外我們還可以在 actions中調用 mutations。在組件中通過 store對象的 dispatch方法來調用 actions里的方法。

modules有點像命名空間,將邏輯關係相近的變數和操作放到一個 module中,個人感覺一般情況用不上這個功能,感興趣的可以看一下官方文檔:https://vuex.vuejs.org/guide/modules.html

二、如何在 vue中使用 vuex

了解了相關概念之後,我們進入實戰,如何在 vue項目中使用 vuex。

第一步先在項目中安裝 vuex,使用下面的命令:

npm install --save vuex  或者  cnpm install --save vuex

然後創建一個 store.js文件,內容如下:

import Vue from 'vue'  import Vuex from 'vuex'    Vue.use(Vuex)    export default new Vuex.Store({      state: {      },      mutations: {      },      actions: {      },      getters: {      }  })

我們可以把有關 vuex的程式碼全部放在這個文件里,但是現在我們還沒有把 vuex添加到 vue的環境中,還要打開 main.js文件做一點修改:

// The Vue build version to load with the `import` command  // (runtime-only or standalone) has been set in webpack.base.conf with an alias.  import Vue from 'vue'  import App from './App'  import store from './store'    Vue.config.productionTip = false    /* eslint-disable no-new */  new Vue({    el: '#app',    store,    components: { App },    template: '<App/>'  })

這裡我們做的操作主要是 import上面創建的 store文件,然後將 store對象添加到 vue的初始化參數里。這樣我們就可以在 vue的組件中通過 this.$store 來訪問 store對象了。

下面我們看看怎麼在組件里使用 store.

我們現在 store.js文件中定義一些 state變數

import Vue from 'vue'  import Vuex from 'vuex'    Vue.use(Vuex)    export default new Vuex.Store({      state: {          count: null,      },      mutations: {          increase(state) {              // count自增              state.count++          }      },      actions: {          initCount(state) {              console.log('init')              // 初始化 count,模擬網路請求              return new Promise((success, reject) => {                  // 延時5000毫秒初始化count                  setTimeout(() => {                      state.count = 0;                      success();                  }, 5000)              })          }      },      getters: {          doubleCount(state) {              // 返回2*count              return 2 * state.count          }      }  })

然後創建一個 Count組件,程式碼如下:

// Count.vue  <template>      <div>          <div>count: {{count?count:'未初始化'}}</div>          <div>doubleCount: {{count?doubleCount:'未初始化'}}</div>      </div>  </template>    <script>  export default {      name: 'Count',      data(){          return {            }      },      mounted(){          this.$store.dispatch('initCount').then(()=>{              setInterval(()=>{                  // 每隔 1s count自增一次                  this.$store.commit('increase')              }, 1000)          })      },      computed: {          // 使用 computed動態更新 count的值,直接放在 data中不能動態更新          // 因為直接放在 data中的話只是一個賦值操作          count(){              return this.$store.state.count          },          doubleCount(){              return this.$store.getters.doubleCount          }      }  }  </script>
// App.vue  <template>      <div id="app">          <Count></Count>      </div>  </template>    <script>  import Count from "./components/Count.vue"    export default {      name: 'app',      components: {          Count      }  };  </script>    <style>  * {      padding: 0;      margin: 0;  }    html,  body,  #app {      width: 100%;      height: 100%;      color: #2c3e50;  }    #app {      display: flex;      justify-content: center;      align-items: center;  }  </style>

運行結果:

未初始化