IT이야기

Vue.js에 대해 Vuex에 액세스할 수 있는 Utils 클래스를 만드는 방법$store

cyworld 2022. 7. 25. 22:47
반응형

Vue.js에 대해 Vuex에 액세스할 수 있는 Utils 클래스를 만드는 방법$store

Vuex에서 상태를 가져오는 경우가 있습니다.this.$store조사해보니 인스턴스 메서드를 설치하는 커스텀 플러그인이 효과가 있을 것 같습니다.

플러그인 로직은 다음과 같습니다.

인덱스.ts

import _ from 'lodash'

export default {
  install: function (Vue) {
    Vue.prototype.$fetchVillager = function () {
      const players = this.$store.state.players
      const village = this.$store.state.villages.find(value => value.id === 0)
      const villagerIds = village.villagers

      const villagers = _.filter(players, function (player) {
        return villagerIds.includes(player.id)
      })
      if (!_.isNil(villagers)) {
        return villagers
      }
      return []
    }
  }
}

보시는 바와 같이this.$store.state.players따라서 Vuex 상태에 액세스하고 있습니다.이 모든 것을 사용하는 것은 매우 간단하며, 여기서 볼 수 있듯이 동작합니다.

computed: {
    villagers: function () {
      return this.$fetchVillager()
    }
  }

하지만 내가 사용했기 때문에Vue.use(MyPlugin)이제 이 기능은 어디에서나 사용할 수 있습니다.사용하고 싶은 컴포넌트(ATM은 3개)로 한정하고 싶습니다.

그래서 기본적으로는 간단한 걸 갖고 싶어요import VillageServices from '@/services/villageServices.ts거기서부터 노출된 기능을 사용하면 됩니다.이 방법으로는 Vuex에 액세스할 수 없기 때문에 이 방법은 확실히 작동하지 않습니다.this.$storeImport된 클래스로 Vue 인스턴스에 바인딩되어 있지 않기 때문입니다.

제가 하고 싶은 일을 이룰 수 있는 방법이 있을까요?

그냥 믹스인이 필요할 것 같아요.

const villagers = {
    methods: {
        $fetchVillagers() {
            // use this.$store
        }
    }
};

const myComponent = new Vue({
    mixins: [villagers],
    computed: {
        villagers() {
            return this.$fetchVillagers();
        }
    }
});

언급URL : https://stackoverflow.com/questions/63455976/how-to-create-a-utils-class-for-vue-js-that-has-access-to-vuex-this-store

반응형