侦听Vuex商店中的浏览器事件

时间:2019-11-26 19:19:08

标签: javascript vue.js vuex

我想为我的Vue应用程序提供Gamepad支持。我想听听来自Gamepad API的事件。

我不想将这些侦听器附加到组件,因为我必须全局处理它们。那么我应该把那些听众放在哪里呢?我应该将每个事件添加到 App.vue 组件中,因为它是应用程序的根目录?

我想用Vuex处理游戏手柄的输入和状态。有没有一种方法可以通过动作(或突变)直接监听浏览器事件?设置我的动作(如...

export default {
  on_browser_gamepadconnected: ({ commit }, e) => {
    // do something
  },
};

1 个答案:

答案 0 :(得分:2)

制作自己的Vuex插件

https://vuex.vuejs.org/guide/plugins.html

您的基本Vuex商店将如下所示。

const state = {
  humans_gone: false
}

const getters = {

}

const mutations = {
  markAsDestroyed(state, value){
     state.humans_gone = value
  }
}

const actions = {
  async destroyAllHumans({ commit, dispatch, state }, exceptMyFriends) {
    // Do stuff
  }
}

const plugins = [
  store => {
    window.addEventListener("gamepadconnected", async e => {
      await store.dispatch('destroyAllHumans', true)
      store.commit('markAsDestroyed', true)
      console.log(`If this is ${store.state.humans_gone}, then I am all done`)
    })
  }
]

export default {
  state,
  getters,
  mutations,
  actions,
  plugins
}
相关问题