第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

Action

1. 前言

本小節(jié)我們將介紹如何使用 Action。包括如何定義 Action、分發(fā) Action、mapActions 輔助函數(shù)的使用方式。Action 在 Vuex 中會大量使用,學好如何使用 Action 非常重要。Action 并不是一個難點,它的使用非常簡單,接下來我們就一步步學習它的使用。

2. Action 簡介

Action 類似于 Mutation,不同的是:

    1. Action 提交的是 mutation,而不是直接變更狀態(tài)。
    1. Action 可以包含任意異步操作。在 vuex 的使用過程中,我們可以將多個 Mutation 合并到一個 Action 中,也可以通過 Action 進行異步操作。

3. 基礎用法

3.1 定義 action

Action 函數(shù)接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調用 context.commit 提交一個 mutation,或者通過 context.state 和 context.getters 來獲取 state 和 getters。

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    // 同步 action
    increment (context) {
      context.commit('increment')
    },
    // 異步 action
    incrementAsync (context) {
      setTimeout(() => {
        context.commit('increment')
      }, 1000)
    }
  }
})

實踐中,我們會經(jīng)常用到 ES2015 的參數(shù)解構來簡化代碼(特別是我們需要調用 commit 很多次的時候):

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

3.2 分發(fā) Action

Action 通過 store.dispatch 方法觸發(fā):

store.dispatch('increment')

3.3 提交載荷(Payload)

你可以向 store.dispatch 傳入額外的參數(shù),即 Actions 的 載荷(payload):

action: {
  increment ({commit}, payload) {
    // 具體 action 內容
  }
}
store.dispatch('increment', {count: 10})

3.4 對象風格的提交方式

提交 action 的另一種方式是直接使用包含 type 屬性的對象:

store.dispatch({
  type: 'increment',
  count: 10
})

當使用對象風格的提交方式,整個對象都作為載荷傳給 action 函數(shù),因此 handler 保持不變:

actions: {
  increment ({commit}, payload) {
    // 具體 action 內容
  }
}

完整示例:

實例演示
預覽 復制
復制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div>購物車數(shù)量:{{count}}</div>
    <button @click="add">同步 +1</button>
    <button @click="addAsync">1s后 +1</button>
    <button @click="addAsyncParams">2s后 +1</button>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.1.2/dist/vuex.js"></script>
<script type="text/javascript">
  const store = new Vuex.Store({
    state: {
      count: 0
    },
    mutations: {
      increment(state) {
        state.count++
      }
    },
    actions: {
      increment ({commit}) {
        commit('increment')
      },
      incrementAsync ({commit}) {
        setTimeout(() => {
          commit('increment')
        }, 1000)
      },
      incrementAsyncParams ({commit}, payload) {
        setTimeout(() => {
          commit('increment')
        }, payload.time)
      }
    }
  })
  var vm = new Vue({
    el: '#app',
    store,
    methods: {
      add() {
        this.$store.dispatch('increment')
      },
      addAsync() {
        this.$store.dispatch({
          type: 'incrementAsync',
        })
      },
      addAsyncParams() {
        this.$store.dispatch('incrementAsyncParams', {
          time: 2000
        })
      },
    },
    computed: {
      count() {
        return this.$store.state.count
      }
    }
  })
</script>
</html>

運行案例 點擊 "運行案例" 可查看在線運行效果

代碼解釋
JS 代碼第 9-11 行,我們定義了 mutation 事件 increment,事件對 state.count + 1。
JS 代碼第 15-17 行,我們定義了同步 Action increment,Action 中直接提交事件 increment。
JS 代碼第 18-22 行,我們定義了異步 Action incrementAsync,1 秒后提交事件 increment。
JS 代碼第 23-27 行,我們定義了接收參數(shù)的異步 Action incrementAsyncParams。
JS 代碼第 35 行,分發(fā) Action 事件 increment。
JS 代碼第 38-40 行,以對象的形式分發(fā) Action 事件 incrementAsync。
JS 代碼第 43-45 行,分發(fā) Action 事件 incrementAsyncParams,并傳入對應參數(shù)。

4 mapActions 輔助函數(shù)

mapActions 輔助函數(shù)幫助我們簡化提交 action 的寫法。

4.1 mapActions 接收數(shù)組格式的參數(shù)

mapActions 可以接收一個 action 事件名的數(shù)組:

...mapActions([
  // 將 `this.increment()` 映射為 `this.$store.dispatch('increment')`
  'increment'
]),

4.2 mapActions 接收對象格式的參數(shù)

在某些情況,我們需要對 Action 中的函數(shù)名重命名以避免和組件內部的變量沖突,這時候我們可以使用對象的方式接收參數(shù):

...mapActions({
  [別名]: [Action name] 
})
// 例:將 `this.add()` 映射為 `this.$store.dispatch('increment')`
...mapActions({
  add: 'increment'
})

完整示例:

實例演示
預覽 復制
復制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div>購物車數(shù)量:{{count}}</div>
    <button @click="increment">添加</button>
    <button @click="add">別名添加</button>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.1.2/dist/vuex.js"></script>
<script type="text/javascript"> 
  const store = new Vuex.Store({
    state: {
      count: 0
    },
    mutations: {
      increment(state) {
        state.count++
      },
    },
    actions: {
      increment({commit}) {
        commit('increment')
      }
    }
  })
  var vm = new Vue({
    el: '#app',
    store,
    methods: {
      ...Vuex.mapActions([
        'increment'
      ]),
      ...Vuex.mapActions({
        add: 'increment'
      })
    },
    computed: {
      count() {
        return this.$store.state.count
      }
    }
  })
</script>
</html>

運行案例 點擊 "運行案例" 可查看在線運行效果

代碼解釋
JS 代碼第 23-25 行,我們通過 mapActions 將 this.increment () 映射為 this.$store.dispatch (‘increment’)。
JS 代碼第 26-28 行,我們通過 mapActions 將 this.add () 映射為 this.$store.dispatch (‘increment’)。

5. 組合 Action

Action 通常是異步的,有時候我們需要知道 action 什么時候結束,并在結束后進行相應的其他操作。更重要的是,我們可以組合多個 action,以處理更加復雜的異步流程。
首先,你需要明白 store.dispatch 可以處理被觸發(fā)的 action 的處理函數(shù)返回的 Promise,并且 store.dispatch 仍舊返回 Promise:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}

現(xiàn)在我們可以:

store.dispatch('actionA').then(() => {
  // ...
})

在另外一個 action 中也可以:

actions: {
  // ...
  actionB ({ dispatch, commit }) {
    return dispatch('actionA').then(() => {
      commit('someOtherMutation')
    })
  }
}

最后,如果我們利用 async /await,我們可以如下組合 action:

// 假設 getData() 和 getOtherData() 返回的是 Promise
actions: {
  async actionA ({ commit }) {
    commit('increment', await getData())
  },
  async actionB ({ dispatch, commit }) {
    await dispatch('actionA') // 等待 actionA 完成
    commit('increment', await getOtherData())
  }
}

完整示例:

實例演示
預覽 復制
復制成功!
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <div>購物車數(shù)量:{{count}}</div>
    <button @click="addAsync">添加</button>
  </div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.1.2/dist/vuex.js"></script>
<script type="text/javascript">
  function getData() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('getData success')
        resolve()
      }, 1000)
    })
  }
  function getOtherData() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        console.log('getOtherData success')
        resolve()
      }, 2000)
    })
  }
  const store = new Vuex.Store({
    state: {
      count: 0
    },
    mutations: {
      increment(state) {
        state.count++
      }
    },
    actions: {
      async actionA ({ commit }) {
        commit('increment', await getData())
      },
      async actionB ({ dispatch, commit }) {
        await dispatch('actionA') // 等待 actionA 完成
        commit('increment', await getOtherData())
      }
    }
  })
  var vm = new Vue({
    el: '#app',
    store,
    methods: {
      addAsync() {
        this.$store.dispatch('actionB')
      },
    },
    computed: {
      count() {
        return this.$store.state.count
      }
    }
  })
</script>
</html>

運行案例 點擊 "運行案例" 可查看在線運行效果

代碼解釋
JS 代碼第 4-19 行,我們定義函數(shù) getData 和 getOtherData。
JS 代碼第 29-31 行,定義 actionA,當 getData 函數(shù)執(zhí)行完成之后 commit increment 事件。
JS 代碼第 32-35 行,定義 actionB,當 dispatch (actionA) 執(zhí)行完成之后 commit increment 事件。

6. 小結

本小節(jié)我們介紹了如何使用 Action 來操作 mutation 或者進行異步操作。主要知識點有以下幾點:

  • 在 store 中定義 Action 事件。
  • 通過 $store.dispatch 分發(fā) Action 事件。
  • 通過 Action 處理異步操作、合并處理 Mutation。
  • 使用 mapActions 方法簡化分發(fā) Action 的寫法。