Answer the question
In order to leave comments, you need to log in
Getter caching with arguments?
Hello. Could you tell. I use getter function
checkTodo: ( state ) => (id) => {
console.log( 'checkTodo', id )
return state.todos.find(todo => todo.id===id ).done
}
Like computed properties, getter results are cached based on their dependencies and will only be recalculated when one of its dependencies changes.
import Vuex from 'vuex'
import { mapGetters, mapMutations } from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
todos: [
{ id: 1, text: 'First', done: true },
{ id: 2, text: 'Second', done: false },
{ id: 3, text: 'Thirh', done: false }
]
},
getters: {
allTodos( state ) { return state.todos },
checkTodo1( state ) {
console.log( 'checkTodo 1' )
return state.todos.find(todo => todo.id===1).done
},
checkTodo: ( state ) => (id) => {
console.log( 'checkTodo', id )
return state.todos.find(todo => todo.id===id ).done
}
},
mutations: {
toggleDone( state, id ) {
const todo = state.todos.find(el => el.id === id );
todo.done = !todo.done;
}
}
})
new Vue({
el: '#app',
store,
template: `
<ul>
<li v-for='todo in allTodos'>
{{ checkTodo(todo.id) }}
<button @click='toggleDone(todo.id)'>
{{todo.text}}
</button>
</li>
<li> {{checkTodo1 }}</li>
</ul>`,
computed: {
... mapGetters(['allTodos', 'checkTodo', 'checkTodo1'])
},
methods: {
...mapMutations(['toggleDone'])
}
})
Answer the question
In order to leave comments, you need to log in
state.todos changes, so it makes sense that all setters are updated. It is right.
Most likely, there is no caching method for such cases, and it is not really necessary)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question