Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何为Vue.js创建有权访问Vuex this.$store的Utils类_Typescript_Vue.js_Vuex - Fatal编程技术网

Typescript 如何为Vue.js创建有权访问Vuex this.$store的Utils类

Typescript 如何为Vue.js创建有权访问Vuex this.$store的Utils类,typescript,vue.js,vuex,Typescript,Vue.js,Vuex,我想从Vuexthis.$store获取状态。我研究发现,让一个自定义插件安装一个实例方法就可以了 这是我的插件逻辑: index.ts import _ from 'lodash' export default { install: function (Vue) { Vue.prototype.$fetchVillager = function () { const players = this.$store.state.players const vil

我想从Vuex
this.$store
获取状态。我研究发现,让一个自定义插件安装一个实例方法就可以了

这是我的插件逻辑:

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 []
    }
  }
}
正如您所看到的,我正在使用
这个.store.state.players
,因此正在访问Vuex状态。使用所有这些都非常简单,正如您在此处所看到的:

computed: {
    villagers: function () {
      return this.$fetchVillager()
    }
  }
然而,自从我使用了
Vue.use(MyPlugin)
之后,这个函数现在到处都可用。我有点想把它限制在我想使用的组件上(有三个atm)

因此,基本上我希望有一个简单的
从'@/services/VillageServices.ts
导入VillageServices,然后从那里使用公开的函数。这肯定行不通,因为使用这种方法无法访问Vuex
this.$store
,因为我没有绑定到带有该导入类的Vue实例


有什么方法可以实现我想做的吗?

我想你可以用一个简单的方法


我想你可以简单地使用一个


我读到关于混合是一种不好的使用模式,如果可能的话应该避免-这就是为什么我省略了它们我不知道你从哪里读到的,但这是一个非常值得怀疑的观点。混血儿不是错误地存在的。它们正是你需要的工具。我读到混合是一种不好的使用模式,如果可能的话应该避免——这就是为什么我省略了它们。我不知道你从哪里读到的,但这是一个非常值得怀疑的观点。混血儿不是错误地存在的。这正是你需要的工具。
const villagers = {
    methods: {
        $fetchVillagers() {
            // use this.$store
        }
    }
};

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