programing

소품을 통한 상태 속성 전달(Vuex)

copysource 2022. 8. 28. 21:25
반응형

소품을 통한 상태 속성 전달(Vuex)

스토어의 데이터를 표시해야 하는 컴포넌트가 있습니다만, 그 컴포넌트는 재사용이 가능하기 때문에 다음과 같이 스토어 모듈의 이름과 속성명을 소품으로 전달하고 싶습니다.

<thingy module="module1" section="person">

그런 다음 구성 요소에서 다음을 수행합니다.

<template>
  <h2>{{ title }}</h2>
  <p>{{ message }}</p>
</template>

<script>
import { mapState } from 'vuex';
import get from 'lodash.get';

export default {
  props: [
    'module',
    'section',
  ],
  computed: mapState(this.module, {
    title: state => get(state, `${this.section}.title`),
    message: state => get(state, `${this.section}.message`),
  })
}
</script>

문제는 그 당시에 소품들이 정의되지 않은 것 같다는 겁니다mapState()실행됩니다.프로펠러 값을 하드코드하면 컴포넌트가 동작합니다.그리고 소품들을 로그로 만들면created()훅, 기대치를 얻을 수 있습니다.레이스 조건인 것 같아요.

내가 여기서 잘못된 방향으로 가고 있는 건가요?

갱신하다

모듈 네임스페이스는 다음과 같이 매핑 함수 내에서 전달되어야 합니다.

computed: mapState({
  title() {
    return get(this.$store.state, `${this.module}.${this.section}.title`);
  },
  message() {
    return get(this.$store.state, `${this.module}.${this.section}.message`);
  }
})

(주의:get()vue 함수가 아닌 lodash입니다.)

이것은 믹스인으로 더욱 추상화될 수 있다.

의 코멘트에 주의해 주세요.

// to access local state with `this`, a normal function must be used
countPlusLocalState (state) {
  return state.count + this.localCount
}

화살표 기능을 사용하고 있습니다.

에 대해서는this.module바인딩 도우미 표기법을 버리고 모듈 참조를 정의에 명시적으로 넣어야 합니다.내 생각엔...

computed: mapState(this.module, {
  title(state) {
    return get(`${state}.${this.module}`, `${this.section}.title`);
  },
  message(state) {
    return get(`${state}.${this.module}`, `${this.section}.message`);
  }
})

언급URL : https://stackoverflow.com/questions/43001181/pass-state-property-via-props-vuex

반응형