Defining reactive state properties and computed getters in Vuex.
State & Getters
State
State là object chứa toàn bộ dữ liệu chia sẻ, là single source of truth của store.
Truy cập trong component qua this.$store.state:
State của Vuex là reactive. Component dùng state trong computed sẽ tự cập nhật khi state đổi.
mapState
Khi cần nhiều state, viết từng computed thủ công dài dòng. mapState sinh computed tự động.
...mapState([...]) trộn các computed vào, dùng this.count, this.user như computed bình thường. Kết hợp với computed cục bộ bằng spread operator.
Getters
Getter là giá trị dẫn xuất từ state, vai trò như computed nhưng ở cấp store. Có cache theo dependency, chỉ tính lại khi state phụ thuộc đổi. Dùng khi nhiều component cần cùng một logic tính toán từ state.
Truy cập qua this.$store.getters:
Method-style getter
Getter trả về function để nhận tham số. Dạng này không cache (chạy mỗi lần gọi).
mapGetters
Trộn getter vào computed tương tự mapState.
State vs Getter
Tips cho AEM
Khởi tạo state ban đầu từ dữ liệu server-side. Sling Model serialize JSON, clientlib parse và đưa vào state khi tạo store, các component đọc qua getter.