The source code for this blog is available on GitHub.

Blog.

Storeについてまとめ

Cover Image for Storeについてまとめ

データの流れを追ってみる

Nuxtでstoreの扱いが分からなかったのでまとめ storeの役割は状態管理、vuesはそのためのライブラリという立ち位置になっている。 nuxtのstoreもvuexをベースにしている

https://vuex.vuejs.org/ja/

Vue Vuex -- Getting started - WDstack - Medium

Nuxtのstoreには、クラシックモードとモジュールモードという記述方法がある。 クラシックモードは、vuexをインポートし1ファイルでmutations,actionsまでを担保している。ただし、廃止予定。

  • Mutationは、Stateの情報を更新する処理を担当
  • Stateは、状態やデータを管理する担当
  • Actionは、Mutationをcommit(呼び出し)できる。また非同期処理も担当
  • Getterは、Stateをfilter等した処理を、サービスで共通化しviewに投げる担当(自信ない...

Actionのdispatchの役割は、非同期処理における完了したときのトリガーを担当

https://blog.mintsu-dev.com/posts/2019-04-21-nuxt-vuex/

やってみる

とりあえず、最も簡単に実装できる単位で理解してみる

https://qiita.com/ekzemplaro/items/b5fad3925127904dca84

store/demo.jsは以下にしている。

export const state = () => ({
  counter: 0
})
export const mutations = {
  add (state) {
    state.counter += 1
  },
  subtract (state) {
    state.counter -= 1
  },
  clear (state) {
    state.counter = 0
  }
}

storedemo.vueは以下。

<template>
  <section>
    <div>{{ counter }}回</div>
    <button @click="addCount">
      add
    </button>
    <button @click="subtractCounter">
      down
    </button>
    <button @click="clearCount">
      clear
    </button>
  </section>
</template>
<script>
      export default {
  computed:{
    count () {
      return this.$store.state.demo.counter
    }
  },
  methods:{
    addCount (e) {
      this.$store.commit('demo/add')
    },
    subtractCounter (e) {
      this.$store.commit('demo/subtract')
    },
    clearCount (e) {
      this.$store.commit('demo/clear')
    }
  }
}

</script>

以下の様も記述できる

<script>
import { mapState, mapMutations } from 'vuex'

export default {
  computed: {
    ...mapState('demo', [
      'counter'
    ])
  },
  methods: {
    ...mapMutations({
      addCount: 'demo/add',
      subtractCounter: 'demo/subtract',
      clearCount: 'demo/clear'
    })
  }
}
</script>

https://qiita.com/y-miine/items/028c73aa3f87e983ed4c


More Stories