vuex getters
- Define a Vuex getter function by using the
getters
property in the Vuex store module. - Access the getter function from within a component using the
mapGetters
helper function or by directly referencing it in the component's computed property. - The getter function receives two arguments: the state object and other getters. You can use these arguments to compute and return a value based on the state or other getters.
- Use the getter function in the component's template or computed property to access the computed value.
Here is an example of how to define and use a Vuex getter:
- In the Vuex store module:
// store/module.js
const module = {
state: {
todos: [
{ id: 1, text: 'Learn Vue', done: true },
{ id: 2, text: 'Build an app', done: false },
{ id: 3, text: 'Deploy to production', done: false }
]
},
getters: {
completedTodos: state => {
return state.todos.filter(todo => todo.done)
}
}
}
- In the component:
// MyComponent.vue
<template>
<div>
<h1>Completed Todos:</h1>
<ul>
<li v-for="todo in completedTodos" :key="todo.id">
{{ todo.text }}
</li>
</ul>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['completedTodos'])
}
}
</script>
In this example, the completedTodos
getter function filters the todos
array in the store module and returns only the todos that are marked as done. The getter is then used in the component's template to display the completed todos.
I hope this explanation helps! Let me know if you have any further questions.