Programing

Vuex의 getter에 매개 변수를 전달하다

c10106 2022. 3. 27. 13:34
반응형

Vuex의 getter에 매개 변수를 전달하다

나는 다음과 같은 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>

구성요소에 소품으로 들어오는 매개변수 색인이 게터에게 성공적으로 전달되었다.

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)템플릿 부분에서 계속 반복한다.내 모든 게터들은 지수를 소품으로 가지고 다녀야 하니까, 그냥 좀 해줬으면 좋겠어.getterName템플릿과 스크립트 파트에서 다음과 같은 내용을 참조하십시오.

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

여기서 코드스타일을 향상시키는 것이 가능한가?

사물을 건조하게 유지하려면 아이템을 얻는 논리를 활용하는 것이 이치에 맞을 것이다.index(상점에 해당) 정보에 해당하므로 구성요소는 렌더링할 준비가 된 전체 데이터만 수신한다.

제안 솔루션은 단일 Getter를 생성하여 이를 수용하는 것이다.index인수 및 반환 옵션의 전체 목록getters.widgetsConfig.

필요한 경우 필요한 정보를 단일 개체로 수집하기 위해 다른 게터를 다시 사용할 수 있다는 점에 유의하십시오.

가능한 구현:

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

구성 요소를 업데이트하여 단일 게이터를 매핑하고 계산된 속성에 사용하십시오.

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

그리고 템플릿 내에서 모든 속성은 다음을 통해 액세스할 수 있다.item.type,item.height,item.width등등..

당신은 항상 getter의 결과를 반환하는 계산된 속성을 만들 수 있다.다음과 같은 경우:

export default {
  props: ['index'],
  computed: {
    ...mapGetters([
      'getTypeFromIndex',
      'getWidthFromIndex',
      'getHeightFromIndex'
    ]),
    height(): { return this.getHeightFromIndex(index) },
    width(): { return this.getWidthFromIndex(index) },
    type(): { return this.getTypeFromIndex(index) },

    //going a step further to clean up your templates...
    classList: [
        "block", 
        "height"+this.height,
        "width"+this.width,
    ]
  }

그래야 네가 필요한 거야height대신 템플릿에height(index), 또는 심지어 단지classList그렇게까지 생각한다면

이것은 또한 여기서 언급된다: https://github.com/vuejs/vuex/issues/688 그리고 나는 그것을 찾을 수 없지만 나는 또한 Evan You가 추천한 것을 Github 이슈에서 본 적이 있다.

참조URL: https://stackoverflow.com/questions/53289737/pass-parameter-to-getters-in-vuex

반응형