javascript - 将参数传递给 Vuex 中的 getter

标签 javascript vue.js vuejs2 vuex

我有一个这样的 Vue 组件:

<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  props: ['index'],
  computed: {
    ...mapGetters([
      'type',
      'width',
      'height',
      'description',
      'smtTagMeasureUnits',
      'tagValue'
    ])
  }
</script>

<template>
  <div :class='["block","module-"+type(index), "width"+width(index), "height"+height(index)]'>
    <h3>{{ description(index) }}</h3>
    <div class="data">
      <h1>{{ tagValue(index) }}</h1>
      <h2 class="measure">{{ smtTagMeasureUnits(index) }}</h2>
    </div>
  </div>
</template>

<style>
  ...
</style>

作为 prop 进入组件的参数 index 已成功传递给 getters:

getters: {
  ...
  type: (state, getters) => (par) => {
    return getters.widgetsConfig[par].type
  },
  width: (state, getters) => (par) => {
    if (getters.widgetsConfig[par].width) {
      return getters.widgetsConfig[par].width
    } return 2
  },
  height: (state, getters) => (par) => {
    if (getters.widgetsConfig[par].height) {
      return getters.widgetsConfig[par].height
    } return 1
  },
  ...
}

工作正常,但我对这种代码风格不满意,因为 getterName(index) 在模板部分不断重复。我所有的 getter 都应该带有 index 作为 Prop ,所以我想在模板中只包含 getterName 并且在脚本部分中包含类似这样的内容:

...mapGetters([
'type',
'width',
'height',
'description',
'smtTagMeasureUnits',
'tagValue'
], index)

这里是否有可能实现代码风格的改进?

最佳答案

如果你想让事情保持干燥,那么利用将项目(index 对应的实体)信息获取到商店的逻辑是有意义的,因此组件只接收准备好被渲染。

建议的解决方案是创建一个 getter,它接受 index 作为参数并从 getters.widgetsConfig 返回完整的选项列表。

请注意,如果需要,可以重复使用其他 getter,以便将必要的信息收集到单个对象中。

可能的实现:

getters: {
  ...
  getItemByIndex: (state, getters) => (index) => {
    const { type, height, width } = getters.widgetsConfig[index]
    return {
      type,
      height,
      width
    }
  },
}

并更新组件以映射单个 getter 并在计算属性中使用它:

computed: {
  ...mapGetters([
    'getItemByIndex'
  ]),
  item () {
    return this.getItemByIndex(index)
  }
}

并且所有属性都可以通过 item.typeitem.heightitem.width 等在模板中访问。

关于javascript - 将参数传递给 Vuex 中的 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53289737/

相关文章:

javascript - VueJS : How to force recompile of <template> after modifying dom

javascript - GAS - 等待用户输入数据,然后功能继续

laravel - 为什么我会收到 422 错误代码?

plugins - sublime text 3中Vue模板中Pug语法高亮的方法

css - 如何在范围仅限于组件的vue组件中导入CSS文件?

javascript - 根据 axios GET 请求的响应填充 Vue 数据

javascript - html/php表单计算简单公式的显示结果

javascript - 为什么在 `then` 内返回 Promise.resolve() 会导致创建两个 promise 而不是一个?

javascript - jsf ajax 调用 : executing javascript function in the end

javascript - vuejs 根据值禁用/启用选择