programing

Vue 3 SFC 스크립트 설정 구문을 사용하여 Vuex mapGetters를 사용하는 방법

bestcode 2022. 8. 24. 23:57
반응형

Vue 3 SFC 스크립트 설정 구문을 사용하여 Vuex mapGetters를 사용하는 방법

일반 Vue 3 Composition API에서 Script Setup 구문으로 컴포넌트를 리팩터링하고 있습니다.시작점:

<script lang="ts">
import { defineComponent, computed } from 'vue';
import { mapGetters } from 'vuex';

export default defineComponent({
  name: 'MyCoolBareComponent',
  computed: {
    ...mapGetters('auth', ['isAdmin']),
  },
});
</script>

현재 Vue v3 이행 매뉴얼인SFC Composition API Syntax Sugar(<스크립트 셋업>)는 다음 RFC 페이지에 링크되어 있습니다.https://github.com/vuejs/rfcs/pull/182

계산된 반응 속성을 사용하는 예는 다음과 같습니다.

export const computedMsg = computed(() => props.msg + '!!!')

다음과 같은 Vuex 4 문서가 현재 없기 때문에<scrip setup>구문을 사용할 때 사용하는 방법이 불분명합니다. 아니면 Vuex 4에서 이 문제를 해결하는 올바른 방법은 무엇입니까?

tldr: 최종 결과까지 아래로 스크롤합니다.

현재 더 나은 문서가 제공되고 있습니다.심플한 답변은 다음과 같습니다.mapGetters직접 구현할 수 있습니다.

https://next.vuex.vuejs.org/guide/composition-api.html#accessing-state-and-getters

<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'

const store = useStore()

const count = computed(() => store.getters.count)
</script>

"계산된 자산"으로 전환하고 싶은 고객이 많은 경우 다음과 같은 "직관적"을 사용할 수 있습니다.

const { countIsOdd, countIsEven } = Object.fromEntries(Object.keys(store.getters).map(getter => [getter, computed(() => store.getters[getter])]))

그것을 함수에 넣으면 보기에도 좋다.

const mapGetters = (getters) => {
  return Object.fromEntries(Object.keys(getters).map(getter => [getter, computed(() => getters[getter])]))
}

const { countIsOdd, countIsEven } = mapGetters(store.getters)

그 함수를 파일에 넣고 모듈로 내보냅니다.

// lib.js
import { computed } from 'vue'
import { useStore } from 'vuex'

const mapGetters = () => {
  const store = useStore()
  return Object.fromEntries(Object.keys(store.getters).map(getter => [getter, computed(() => store.getters[getter])]))
}

export { mapGetters }

모든 컴포넌트에서 쉽게 사용할 수 있습니다.

// components/MyComponent.vue
<script setup>
import { mapGetters } from '../lib'

const { countIsOdd, countIsEven } = mapGetters()
</script>

최종 결과:

다음은 제가 생각해낸 마지막 lib.js입니다.

import { computed } from 'vue'
import { useStore } from 'vuex'

const mapState = () => {
  const store = useStore()
  return Object.fromEntries(
    Object.keys(store.state).map(
      key => [key, computed(() => store.state[key])]
    )
  )
}

const mapGetters = () => {
  const store = useStore()
  return Object.fromEntries(
    Object.keys(store.getters).map(
      getter => [getter, computed(() => store.getters[getter])]
    )
  )
}

const mapMutations = () => {
  const store = useStore()
  return Object.fromEntries(
    Object.keys(store._mutations).map(
      mutation => [mutation, value => store.commit(mutation, value)]
    )
  )
}

const mapActions = () => {
  const store = useStore()
  return Object.fromEntries(
    Object.keys(store._actions).map(
      action => [action, value => store.dispatch(action, value)]
    )
  )
}

export { mapState, mapGetters, mapMutations, mapActions }

컴포넌트에서 이것을 사용하는 방법은 다음과 같습니다.

<template>
  Count: {{ count }}
  Odd: {{ counterIsOdd }}
  Even: {{ counterIsEven }}
  <button @click="countUp">count up</button>
  <button @click="countDown">count down</button>
  <button @click="getRemoteCount('https://api.countapi.xyz')">
    get remote count
  </button>
</template>

<script setup>
import { mapState, mapGetters, mapMutations, mapActions } from '../lib'

// computed properties
const { count } = mapState()
const { countIsOdd, countIsEvent } = mapGetters()

// commit/dispatch functions
const { countUp, countDown } = mapMutations()
const { getRemoteCount } = mapActions()
</script>

이에 대한 피드백을 주시면 감사하겠습니다.

아직까지는 이 구문이 효과가 있는 것 같습니다.하지만 Vuex가 템플릿의 컴퓨터 게터를 보다 깔끔하게 노출할 수 있는 방법을 개발했으면 합니다.

더 좋은 방법이 있다면 듣고 싶어요!

<script setup lang="ts">
import { mapGetters } from 'vuex';

export const name = 'MyCoolBareComponent';

export default {
  computed: {
    ...mapGetters('user', ['profile', 'roles']),
  },
};
</script>

아무것도 내보낼 필요가 없습니다.SFC는 모든 변수와 컴포넌트를 등록하여 다음 사이트에서 사용할 수 있도록 합니다.template.

SFC는 컴포넌트 이름을 파일 이름에서 자동으로 추론합니다.

다음은 도움이 될 수 있는 몇 가지 예입니다.

<script setup>
import { computed } from 'vue'
import { useStore } from 'vuex'

import MyComponent from './components/MyComponent'

const store = useStore()

const data = 'Random string as a data'

// without module/data 
const myAction = () => store.dispatch('myAction')
// with data
const mySecondAction = () => store.dispatch('mySecondAction', data)

// with module
const myMutation = () => store.commit('moduleName/myMutation')
// with module/data
const myNewMutation = () => store.commit('moduleName/myNewMutation', data)

const myStateVariable = computed(() => store.state.myStateVariable)
// with module
const myGetter = computed(() => store.getters.moduleName.myGetter)

// replace using of mapState/mapGetters
const state = computed(() => store.state)

// and then
console.log(state.myStateVariable)
console.log(state.mySecondStateVariable)
....

</script>

이런 거 할 수 있어요.

import { mapGetters } from "vuex"
setup() {
  return {
    ...mapGetters("myModule", ["doSomething"])
  }
}

언급URL : https://stackoverflow.com/questions/64010072/how-to-use-vuex-mapgetters-with-vue-3-sfc-script-setup-syntax

반응형