0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vue.js Vuex編(シンプルなカウンターアプリケーション)

Posted at

実行環境

macOS Catalina バージョン 10.15.7
MacBook Pro 13インチ
Vue 2.6.12

カウンターアプリケーション

vuexを用いてカウンターアプリケーションを作成する。まず、プロジェクト内でvuexをインストールする。

npm install vuex

その後、srcディレクトリの直下にstore.jsを作成する。シンプルなVuexStoreを記述する。(main.js内でstoreをインポートしてvueインスタンス内に記述しないとvuexを使うことができないので注意。)

store.js

// vue,vuexをインポート
import Vue from 'vue'
import Vuex from 'vuex'

// vuexプラグインの使用の宣言
Vue.use(Vuex)

// シンプルなVuexStore
const store = new Vuex.Store({
    state: {
        count: 0,
    },
    mutations: {
        increment(state) {
            state.count++
        }
    }
})

// storeをエクスポート
export default store

stateに格納されているデータは直接変更することはできない。ミューテーションをコミットすることによって値の更新をすることができる。ミューテーションの中で定義する関数の引数にはstateが必要となる。
次にApp.vueの子コンポーネントとしてCount.vueを作成する。

Count.vue
<template>
    <div>
        <h3>カウンターアプリケーション</h3>
        <button @click="increment">+1</button>
        <p>{{ count }}</p>
    </div>
</template>

<script>
export default {
    computed: {
        count() {
            return this.$store.state.count
        },
    },
    methods: {
        increment() {
            this.$store.commit('increment')
        },
    }
}
</script>

コンポーネントから値を更新する際、this.$store.commit('increment')のようにしている部分がミューテーションをコミットしている部分である。

スクリーンショット 2020-12-15 10.23.09.png

最後に

今回は非常にシンプルなカウンターアプリケーションを作成した。次の記事でgetters,mutations,actionsについてまとめようと思う。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?