programing

Vuex 저장소에서 브라우저 이벤트 듣기

prostudy 2022. 8. 7. 16:24
반응형

Vuex 저장소에서 브라우저 이벤트 듣기

Vue 앱에 Gamepad를 지원하고 싶습니다.Gamepad API에서 이벤트를 듣고 싶습니다.

이러한 청취자는 글로벌하게 취급해야 하기 때문에 컴포넌트에 접속하고 싶지 않습니다.그럼 그 청취자들을 어디에 연결하면 될까요?App.vue 컴포넌트는 앱의 루트이기 때문에 각 이벤트를 App.vue 컴포넌트에 추가해야 합니까?

Vuex에서 게임패드의 입력과 상태를 처리하고 싶습니다.동작(또는 돌연변이)을 통해 브라우저 이벤트를 직접 들을 수 있는 방법이 있습니까?내 행동을 이렇게 세팅하면 정말 좋을 것 같아.

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

자체 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
}

언급URL : https://stackoverflow.com/questions/59057998/listening-to-browser-events-from-the-vuex-store

반응형