使用 mapState 和 mapGetters 进行简化

作为我们将介绍 Vuex 的最后一个功能之一,让我们看看 mapStatemapGetters。这些是方便的实用程序,可帮助将状态值和 getter 映射到组件的计算属性中。实际上,它使您的 HTML 模板更加简单。因此,您可以简单地使用 {{ firstName }},而不是 {{ $store.state.firstName }}。您可以只使用 {{ name }},而不是使用 {{ $store.getters.name }}

mapStatemapGetters 都可以接收要映射的值数组或对象,其中每个键代表您希望在组件中使用的名称(name),值是 Vuex 存储中的状态值或 getter。它们都与 Vue 应用程序的计算块一起使用。

在第一个示例中,两个状态值和三个 getter 仅通过它们的名称进行映射:

mapState(["age", "rank", "serialNumber"]);
mapGetters(["name", "fiction", "nonfiction"]);

但是,如果这些名称可能太通用,或者可能与现有数据冲突,您可以为它们指定其它名称:

mapState({
    howOld:"age",
    level:"rank",
    sn:"serialNumber"
});
mapGetters({
    ourName:"name",
    fictionBooks:"fictionBooks",
    nonfictionBooks: "nonfictionBooks"
});

为了同时使用 mapStatemapGetters,您需要首先导入它们:

import { mapState, mapGetters } from 'vuex';

使用这两个功能肯定会有助于减少您为使用 Vuex 编写的代码量。

您将在以下练习的帮助下了解如何添加 mapStatemapGetters

练习9.06:添加 mapState 和 mapGetters

让我们看一个简单的例子。在 Exercise 9.02 中,我们使用 getter 创建了获取名称值的快捷方式。我们可以通过应用我们刚刚学到的知识来简化该代码。我们可以使用映射函数来简化我们的代码。

要访问本练习的代码文件,请参阅 https://packt.live/3ldBxpb

  1. 使用 Vuex 创建一个新的 Vue 应用程序,然后将 store(位于 store/index.js)复制到这个新版本中。您将需要名字和姓氏的状态值,以及返回完整名称的 getter:

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
        state: {
            firstName: "Lindy",
            lastName: "Roberthon"
        },
        getters: {
            name(state) {
                return `${state.firstName} ${state.lastName}`;
            }
        }
    })
  2. 编辑主要组件。您将需要编辑存储中的所有三个值(状态值和 getter),但使用 mapStatemapGetters 来简化它:

    <template>
        <div id="app">
            <p>
                My name is {{ firstName }} {{ lastName}}, or just {{ name }}.
            </p>
        </div>
    </template>
    
    <script>
    import { mapGetters } from 'vuex';
    import { mapState } from 'vuex';
    
    export default {
        name: 'app',
        computed: {
            ...mapState([ "firstName", "lastName" ]),
            ...mapGetters([
                "name"
            ])
        }
    }
    </script>

正如您所看到的,通过使用 mapStatemapGetters,我们为应用程序的模板部分提供了一种更简单地使用数据的方法:

My name is Lindy Roberthon, or just Lindy Roberthon.

完成后,您应该看到与之前看到的完全相同的输出。重要的是,您需要编写的代码量减少了!

在下一节中,我们将简要讨论 mapMutationsmapActions