For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/frontend/vue2.7/vuex/actions.md.

Managing asynchronous business logic with Vuex actions.

Actions

Action chứa logic nghiệp vụ, có thể bất đồng bộ (gọi API), và commit mutation để đổi state. Component dispatch action thay vì commit mutation trực tiếp khi có xử lý phức tạp hoặc async.

Định nghĩa và dispatch

Action nhận context (có commit, dispatch, state, getters) và payload.

actions: {
  increment(context) {
    context.commit('increment')
  }
}
this.$store.dispatch('increment')

Thường destructure context cho gọn:

actions: {
  incrementBy({ commit }, payload) {
    commit('incrementBy', payload)
  }
}

Action bất đồng bộ

Đây là lý do chính action tồn tại: xử lý async rồi commit mutation đồng bộ.

actions: {
  async fetchProducts({ commit }) {
    commit('setLoading', true)
    try {
      const res = await fetch('/bin/products.json')
      const data = await res.json()
      commit('setProducts', data)
    } catch (e) {
      commit('setError', e.message)
    } finally {
      commit('setLoading', false)
    }
  }
}
this.$store.dispatch('fetchProducts')

dispatch trả về Promise

Action async trả về Promise, cho phép chờ hoàn tất hoặc nối chuỗi.

this.$store.dispatch('fetchProducts').then(() => {
  console.log('xong')
})
// gọi action khác bên trong action
actions: {
  async initApp({ dispatch }) {
    await dispatch('fetchUser')
    await dispatch('fetchProducts')
  }
}

mapActions

Trộn dispatch thành methods.

import { mapActions } from 'vuex'

export default {
  methods: {
    ...mapActions(['fetchProducts']),

    ...mapActions({
      load: 'fetchProducts'
    })
  }
}
<button @click="fetchProducts">Tải</button>

Mutations vs Actions

MutationsActions
Đổi stateTrực tiếpGián tiếp (qua commit)
AsyncKhông đượcĐược
Gọi bằngcommitdispatch
Chứa logicKhông, chỉ gán stateCó, xử lý nghiệp vụ

Luồng chuẩn: component dispatch action, action xử lý async, action commit mutation, mutation đổi state.

Tips cho AEM

Action là nơi gọi Sling Servlet hoặc AEM API. Endpoint nên lấy từ Sling Model (truyền vào lúc khởi tạo state hoặc qua data attribute) thay vì hardcode, để chạy đúng theo môi trường và context path.

actions: {
  async search({ commit, state }, keyword) {
    const url = `${state.searchEndpoint}?q=${encodeURIComponent(keyword)}`
    const res = await fetch(url)
    commit('setResults', await res.json())
  }
}

Lưu ý context path của AEM (vd /content/site/vn) khi build URL. Lấy base path từ cấu hình server-side thay vì giả định gốc /.