Getters - Raiondesu/Tuex GitHub Wiki
Sometimes one may need to compute some value based on other store values, for example - filtering a list of todos:
computed: {
doneTodosCount () {
return this.$store.todos.filter(todo => todo.done).length
}
}
If more than one component needs to make use of this, we have to either duplicate the function, or extract it into a shared module and import it in multiple places - both cases are less than ideal.
Tuex allows to define getters in the store. These are like computed properties, but for the store.
A Native JavaScript Concept
Getters are already a part of modern JS:
const obj = {
get foo() {
return 'bar';
}
}
console.log(obj.foo); // => 'bar'
They are mostly used as computed properties of JS-objects or for private properties incapsulation. This is the concept any JS developer is already familiar with.
Tuex-Enhanced Getters
As it was with values, getters in Tuex are plain JavaScript getters, that can reference their context as this
:
const tuex = new Tuex.Store({
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
],
get doneTodos() {
return this.todos.filter(todo => todo.done)
}
})
console.log(tuex.store.doneTodos);
// => [ { id: 1, text: '...', done: true } ]
Tuex still keeps track of everything happening inside of the getter and of the getter itself.
In the above example, when console.log
is executed, Tuex gets notified that the getter doneTodos
was accessed and that the value num
was accessed right after.
This gives Tuex the semantic context of a getter, which can help to keep track of the store in the long run.
So, let's rewrite our first example using the doneTodos
getter we wrote earlier:
computed: {
doneTodosCount () {
return this.$store.doneTodos.length
}
}
It's that simple!
Enumerable
Getters in Tuex store are not enumerable, which means that to print or access a certain Tuex getter in a store you need to explicitly state so:
const tuex = new Tuex.Store({
todos: [
{ id: 1, text: '...', done: true },
{ id: 2, text: '...', done: false }
],
get doneTodos() {
return this.todos.filter(todo => todo.done)
}
})
console.log(tuex.store.doneTodos);
// => [ { id: 1, text: '...', done: true } ]
// Will only log 'todos', since getter 'doneTodos' is not enumerable
console.log(Object.keys(tuex.store));
// => [ 'todos' ]