えぐろぐ

https://twitter.com/eggpogg

Nuxtのstoreのサンプル

// store/index.js
export const state = () => ({
  count: 0,
})

export const mutations = {
  increment(state) {
    state.count += 1
  },
  increment_async(state, payload) {
    state.count += payload.value
  },
}

export const actions = {
  async increment({ commit }) {

    const res = await fetch(
      'https://community-open-weather-map.p.rapidapi.com/weather?lat=0&lon=0&callback=test&id=2172797&lang=null&units=%2522metric%2522%20or%20%2522imperial%2522&mode=xml%252C%20html&q=London%252Cuk',
      {
        method: 'GET',
        headers: {
          'x-rapidapi-host': 'community-open-weather-map.p.rapidapi.com',
          'x-rapidapi-key': 'xxxxxxxxxxxxx',
        },
      }
    )

    commit('increment_async', { value: 2 })
  },
}

使い方

console.log(this.$store.state.count) // => 0

this.$store.commit('increment')
await this.$store.dispatch('increment')

console.log(this.$store.state.count) // => 3

思ったよりもサクッと出来て驚いた!