推荐答案
在 Nuxt.js 中使用 Vuex 的 getters 非常简单。你可以通过 this.$store.getters 访问 Vuex store 中的 getters。以下是一个示例:
// www.javascriptcn.com code example
// store/index.js
export const state = () => ({
todos: [
{ id: 1, text: 'Learn Nuxt.js', done: true },
{ id: 2, text: 'Learn Vuex', done: false }
]
})
export const getters = {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}在组件中使用 getter:
// www.javascriptcn.com code example
<template>
<div>
<h2>Done Todos</h2>
<ul>
<li v-for="todo in doneTodos" :key="todo.id">{{ todo.text }}</li>
</ul>
</div>
</template>
<script>
export default {
computed: {
doneTodos() {
return this.$store.getters.doneTodos
}
}
}
</script>本题详细解读
1. Vuex Getters 的作用
Vuex 的 getters 允许你从 store 中派生出一些状态,类似于 Vue 组件中的计算属性。它们可以用于对 store 中的状态进行过滤、计算或格式化。
2. 定义 Getters
在 Vuex store 中,你可以通过 getters 对象定义 getters。每个 getter 函数接收 state 作为第一个参数,并且可以返回任何值。
export const getters = {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
}
}3. 在组件中使用 Getters
在组件中,你可以通过 this.$store.getters 访问 Vuex store 中的 getters。通常,你会将 getters 映射到组件的计算属性中,以便在模板中使用。
computed: {
doneTodos() {
return this.$store.getters.doneTodos
}
}4. 使用 mapGetters 辅助函数
为了简化代码,你可以使用 mapGetters 辅助函数将 store 中的 getters 映射到组件的计算属性中。
// www.javascriptcn.com code example
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'doneTodos'
])
}
}5. 动态 Getters
Getters 也可以接收参数,通过返回一个函数来实现动态 getters。
export const getters = {
getTodoById: state => id => {
return state.todos.find(todo => todo.id === id)
}
}在组件中使用动态 getter:
computed: {
todo() {
return this.$store.getters.getTodoById(this.todoId)
}
}通过以上步骤,你可以在 Nuxt.js 中轻松使用 Vuex 的 getters 来管理和访问 store 中的状态。