0👍
✅
To create your store getters (similar to Vuex’s getters) from a given getters
map:
- Declare a new object to store our new getters (named
myGetters
). - Use
Object.entries()
ongetters
to get its keys and values. - On each key/value pair, use
Object.defineProperty()
onmyGetters
to define a getter that invokes the value (if it’s a function) withstate
as the argument.
function createStore({ state, mutations, getters }) {
1️⃣
const myGetters = {}
if (getters) {
2️⃣
Object.entries(getters).forEach(([key, value]) => {
3️⃣
Object.defineProperty(myGetters, key, {
get: () => typeof value === 'function' ? value(state) : value
})
})
}
return {
//...
getters: myGetters
}
}
Then initialize it in store.js
like this:
const store = createStore({
//...
getters: {
counter: state => state.counter,
half: state => state.counter / 2,
double: state => state.counter * 2,
square: state => Math.pow(state.counter, 2)
}
})
Source:stackexchange.com