I have a situation where I need to retrieve state from the Vuex store using this.$store
. After some research, I discovered that creating a custom plugin with an installed instance method might be the solution.
Here is my plugin implementation:
index.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 []
}
}
}
As you can see, I am utilizing this.$store.state.players
to access the Vuex state. Implementing this functionality is straightforward and it works as intended, as shown here:
computed: {
villagers: function () {
return this.$fetchVillager()
}
}
However, by using Vue.use(MyPlugin)
, this function becomes accessible globally. I would prefer to restrict its usage to specific components where I need it (currently three components).
Ideally, I would like to import VillageServices
from '@/services/villageServices.ts' and leverage the exposed functions from there. Unfortunately, this approach does not allow me to access Vuex's this.$store
since I am not tied to a Vue instance with the imported class.
Is there a way to achieve the desired behavior?