【譯】Vuex—怎樣使用state

當一個app變得複雜,就數據而言,將會被多個組件傳遞使用的時候,那該考慮使用Vuex了。javascript

Vuex是一個狀態維護器,是個Vue的類庫。它爲應用中全部組件提供了(狀態)中心化存儲,它的規則確保了數據的更改只可以經過可預測的方式去作。html

Vuex

爲啥用Vuex?

  • Vuex提供了一個真實的(數據)來源
  • 每一個組件都可以訪問全局的state
  • 這個全局的state響應起來就像本地state同樣(觸手可得)
  • 減小了放在組件裏的data,從而使追蹤數據源變得不那麼複雜
  • Vuex提供了一個模式,使更改狀態變得標準化

用npm來安裝一下Vuex:vue

npm i vuex --savejava

開一個store.js文件,大概長成這樣:vuex

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const store = new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  getters: {},
});
複製代碼

在main.js裏,引入store文件,而後加到Vue裏,讓store和Vue實例關聯了起來。npm

import Vue from 'vue';
import App from './App.vue';
import { store } from './store/store';

Vue.config.productionTip = false;

new Vue({
  store,
  render: h => h(App),
}).$mount('#app');
複製代碼

如今咱們store創建好了,可是還不能訪問和修改它。數組

Vuex是怎樣和store協同的

store

Getters

將Vuex裏的state轉成(Vue組件)的計算屬性裏app

在store.js裏,咱們可以建立getters,這可以直接獲取store裏的state。接着咱們就可以經過計算屬性在組件內顯示getters。異步

getters官方文檔ide

示例以下:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: { id: 'aaa', name: 'Adsasas' },
    events: [
      {
        id: 1,
        title: 'title one',
        organizer: 'a'
      },
      {
        id: 2,
        title: 'title two',
        organizer: 'b'
      },
      {
        id: 3,
        title: 'title three',
        organizer: 'c'
      }
    ],
    categories: [
      'sustainability',
      'nature',
      'animal welfare',
      'housing',
      'education',
      'food',
      'community'
    ]
  },
  mutations: {},
  actions: {},
  getters: {
    catLength: state => {
      return state.categories.length
    },
    doneToDos: state => {
      return state.todos.filter(todo => todo.done)
    },
    activeTodosCount: state => {
      return state.todos.filter(todo => !todo.done).length
    },
    getEventById: state => id => {
      return state.events.find(event => event.id === id)
    }
  }
})
複製代碼

怎樣把getters和組件關聯起來?

答案是使用計算屬性(computed properties),不過咱們可以經過(Vuex的)map器來方便的達到這個目的。

<template>
<div>
  <h1>Create Event {{ userName }}</h1>
  <p>There are {{catLength}} categories</p>
  <ul>
    <li v-for="cat in categories" :key="cat">
        {{cat}}
    </li>
  </ul>
<p>
{{ getEventById(3) }}
</p>
</div>

</template>

<script> import { mapState, mapGetters } from 'vuex' export default { computed: { ...mapState(['user', 'categories']), ...mapGetters(['getEventById', 'catLength']) } } </script>
複製代碼

在計算屬性裏經過展開語法,把getter的名字做爲字符串拼成數組來調用map器,而後咱們就可以在template裏引用這些getter了。

咱們還可以建立帶參數的getter,這些參數能夠從template調用進來。getEventById就是這麼個例子。

Mutations

  • 提交+跟蹤+更改狀態
  • 最佳實踐是調用(提交)mutations,而後讓mutations來直接更新state
  • 使用devtools咱們可以回滾mutations到前一個state
  • Mutations的函數都是同步的,一個接一個地發生。

Mutations

Mutations官方文檔

Actions

  • 能夠是異步的
  • 可以圍繞mutations寫業務邏輯(commit mutations等)
  • (最好)始終把Mutations放在Actions裏 —— 這樣業務邏輯就方便使用,能增長擴展性

Actions官方文檔

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
export const store = new Vuex.Store({
  state: {
    categories: ['travel', 'fun', 'social', 'work', 'other'],
    events: [],
  },
  getters: {
    cat: state => {
      return state.categories;
    },
    getEventById: state => id => {
      return state.events.find(event => event.id === id);
    },
    events: state => {
      return state.events;
    },
  },
  mutations: {
    ADD_EVENT(state, event) {
      state.events.push(event);
    },
  },
  actions: {
    createEvent({ commit }, event) {
      commit('ADD_EVENT', event);
    },
  },
});
複製代碼

這裏咱們能看到mutation已經建立好了,可以把參數event放到events的數組裏。那個action將會調用這個mutation去更新store。

咱們看下如何在組件裏調用這個action。

this.$store.dispatch('createEvent', this.event)

經過(組件中)引用的store(this.$store),調用dispatch方法,用action的名字(做參數),又把this.event傳進了action,而後就能讓mutation來更新state了。

使用以上這種方式來使用Vuex,可以避免在各個組件裏追蹤數據的傳遞。在大型項目裏(以上這種寫法)代碼可能會變得十分臃腫,所以須要模塊化來解決這個問題。模塊化的文檔可以在這裏找到。

以上就是Vuex的基礎~

原文

相關文章
相關標籤/搜索