How to define getters in Vuex
Vuex getters provide computed properties for your store state, enabling derived data calculation with automatic caching and reactive updates. With over 25 years of experience building complex applications and as the creator of CoreUI, I use Vuex getters extensively for data transformation and filtering. The most effective approach is defining getters as functions that receive state as the first argument and return computed values. This ensures efficient data derivation with automatic dependency tracking and caching for optimal performance.
Define Vuex getters as functions that compute derived state values with automatic caching and reactive updates.
// store/index.js
import { createStore } from 'vuex'
const store = createStore({
state: {
users: [
{ id: 1, name: 'John', active: true, role: 'admin' },
{ id: 2, name: 'Jane', active: false, role: 'user' },
{ id: 3, name: 'Bob', active: true, role: 'user' }
],
searchTerm: ''
},
getters: {
// Simple getter
activeUsers: (state) => {
return state.users.filter(user => user.active)
},
// Getter with arguments
getUsersByRole: (state) => (role) => {
return state.users.filter(user => user.role === role)
},
// Getter accessing other getters
activeUserCount: (state, getters) => {
return getters.activeUsers.length
},
// Complex filtered data
filteredUsers: (state) => {
return state.users.filter(user =>
user.name.toLowerCase().includes(state.searchTerm.toLowerCase())
)
}
}
})
// Component usage
export default {
computed: {
...mapGetters(['activeUsers', 'activeUserCount']),
adminUsers() {
return this.$store.getters.getUsersByRole('admin')
}
}
}
This example shows different types of Vuex getters: simple filtering, parameterized getters that return functions, getters that depend on other getters, and complex computed properties. Getters automatically cache their results and only recalculate when their dependencies change, making them efficient for expensive computations.
Best Practice Note:
This getter pattern is used throughout CoreUI’s state management for efficient data derivation. Always use getters for computed state to leverage Vue’s reactivity system and avoid duplicate calculations across components.



