Nuxt.jsの基礎勉強-カウンターアプリを作成-

はじめに

今回はカウンターアプリを作ることでvuexの知識を整理をした。

github.com

カウンターアプリの実装

storeの作成

  • モジュールモードを用いてストアを設計
  • stateにはデータの初期状態を記述
  • mutationsにデータの操作を記述
  • actionsにmutationの読み込み操作を記述
export const state = () =>({
    count: 0
})

export const mutations = {
    countUp: function(state, payload){
        state.count += payload
    },
    resetCount: function(state, payload){
        state.count = payload
    }
}

export const actions = {
    countUpAction: function(state, payload){
        state.commit('countUp', payload)
    },
    resetCountAction: function(state, payload){
        state.commit('resetCount', payload)
    }
}

コンポーネントでカウンターアプリを作成

  • 今回はアクションを介してミューテーションからストアの操作を行なったので、dispatchを使ってデータの送信をActionに送る。
<template>
    <section class="container">
        <p>
            {{ $store.state.counter.count }}
            <button @click="$store.dispatch('counter/countUpAction', 1)">+1</button>
            <button @click="$store.dispatch('counter/resetCountAction', 0)">reset</button>
        </p>

    </section>
</template>

ページでコンポーネントを表示

<template>
    <section class="container">
        <counter />
        <page />
    </section>
</template>

<script>
import counter from '~/components/counter.vue'
import page from '~/components/page.vue'
export default {
    components: {
        counter,
        page
    }    
}
</script>

終わりに

実際に自ら考えて作ってみることで、storeやcomponentsの記述の仕方を再学習するいい機会になった。