【问题标题】:listening to browser events from the Vuex store监听来自 Vuex 商店的浏览器事件
【发布时间】:2019-11-26 19:19:08
【问题描述】:

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

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

我想用 Vuex 处理游戏手柄的输入和状态。有没有办法可以通过操作(/或突变)直接监听浏览器事件?设置我的操作会很棒......

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

【问题讨论】:

    标签: javascript vue.js vuex


    【解决方案1】:

    制作你自己的 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
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-26
      • 2018-01-17
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多