【问题标题】:Alias a single Vue getter in mapGetters在 mapGetters 中为单个 Vue getter 命名
【发布时间】:2020-09-21 02:17:12
【问题描述】:

我有一个带有 getter 的 vuex 模块。我在一个 vue 组件中使用这个模块的 getter:

...
computed: {
    ...mapGetters('myCoolModule', ['isActive', 'someOtherGetter', 'yetAnotherGetter']),
}
...

我还有其他具有isActive getter 的 vuex 模块,所以我想在这里给它起别名。我熟悉对象语法,即,

...
computed: {
    ...mapGetters('myCoolModule', { myCoolModuleIsActive: 'isActive', someOtherGetter: 'someOtherGetter', yetAnotherGetter: 'yetAnotherGetter' }),
}
...

但是,我不需要别名 'someOtherGetter''yetAnotherGetter',而且对象语法似乎要求我这样做。

是否有与 mapGetters 一起使用的语法,以便我只能为其中一个 getter 设置别名?

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    使用两次怎么样?

    computed:
    {
      ...mapGetters('myModule', {
        myCoolModuleIsActive: 'isActive',
      }),
      ...mapGetters('myModule', ['someOtherGetter', 'yetAnotherGetter']),
    }
    

    为什么不对 Vuex 模块进行命名空间呢?因此可以避免这样的名称冲突。

    【讨论】:

    • > 为什么不对 Vuex 模块进行命名空间——我更喜欢只使用模块定义来命名空间。在sampleStore 中,我宁愿不要在属性前面加上sampleStore,我发现这可能有点冗长/冗余。
    • 好吧,那么也许您会发现,按照手册 (vuex.vuejs.org/guide/…) 中的建议使用(全局)常量来命名您的 Vuex getters/mutations/actions 将有助于防止名称冲突。跨度>
    • AFAIK 文档仅使用全局常量进行突变。您是否也将它们用于操作?
    • 是的,我对所有 3 项都使用常量 - getter、mutations 和 actions。我什至在我的事件总线中使用常量 - 作为事件名称。
    猜你喜欢
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2021-11-17
    • 2019-04-11
    • 2017-12-21
    • 2020-11-22
    相关资源
    最近更新 更多