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/introduction.md.

Vuex Introduction - developer documentation and reference notes for Vuex Introduction.

Vuex Introduction

Vuex là thư viện state management tập trung cho Vue. State dùng chung được lưu một nơi (store), mọi component đọc cùng nguồn và thay đổi theo quy tắc rõ ràng. Với Vue 2.7 dùng Vuex phiên bản 3.x (Vuex 4 dành cho Vue 3).

Khi nào cần Vuex

Không phải app nào cũng cần. Truyền props và emit event là đủ cho phần lớn trường hợp. Cân nhắc Vuex khi:

  • Nhiều component ở các nhánh khác nhau cần đọc/ghi cùng một state.
  • State cần tồn tại độc lập với vòng đời của một component.
  • Luồng dữ liệu qua nhiều tầng props/events trở nên khó theo dõi.

Trong AEM, lý do hay gặp: nhiều AEM component (nhiều mount point Vue riêng biệt trên cùng trang) cần chia sẻ chung state, ví dụ giỏ hàng, bộ lọc toàn trang, thông tin user.

Vấn đề Vuex giải quyết

State chia sẻ rải rác giữa các component dẫn tới:

  • Nhiều bản sao state không đồng bộ.
  • Khó biết ai đã thay đổi state và khi nào.

Vuex áp dụng one-way data flow tập trung: component đọc state, dispatch action, action commit mutation, mutation đổi state, view cập nhật.

Các khái niệm cốt lõi

Khái niệmVai trò
StateNguồn dữ liệu tập trung (single source of truth)
GettersGiá trị dẫn xuất từ state, có cache (như computed)
MutationsCách duy nhất đổi state, phải đồng bộ
ActionsChứa logic, có thể bất đồng bộ, commit mutation
ModulesChia store lớn thành các module nhỏ

Cài đặt

npm install vuex@3

Đăng ký plugin và tạo store:

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  getters: {},
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {},
  modules: {}
})

Truyền store vào instance gốc. Mọi component con truy cập qua this.$store.

import Vue from 'vue'
import App from './App.vue'
import store from './store'

new Vue({
  store,
  render: h => h(App)
}).$mount('#app')
// trong component bất kỳ
this.$store.state.count
this.$store.commit('increment')

Tips cho AEM

Mỗi AEM component thường tạo một instance Vue riêng. Để chia sẻ state giữa chúng, tạo một store dùng chung (singleton) trong clientlib và truyền cùng store đó vào mọi instance. Chi tiết ở note AEM Integration.