LoginSignup
2
7

More than 3 years have passed since last update.

【Vue 2】Vuexチートシート

Last updated at Posted at 2021-05-04

Vuexとは

コンポーネント間でデータを共有するため状態管理ライブラリ
いわゆる、グローバル変数のようなものを定義し操作できる

使い方

これ以降、VueCLIで作成を想定して記載

1. Vuexのインストール

Vuexのインストール
$ npm install vuex

2. /src直下にstore.jsを作成

このへんの場所に関してはプロジェクトに応じて設定する
image.png
図. 今回のプロジェクトのディレクトリ構成

3. main.jsのVueインスタンスにVuexを登録

main.js
import Vue from 'vue'
import App from './App.vue'
import store from './store' // 追加行

Vue.config.productionTip = false

new Vue({
  store, // 追加行
  render: h => h(App),
}).$mount('#app')

4. store.jsおよびVueコンポーネントを実装

store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// Vuexインスタンス生成
export default new Vuex.Store({
  // state: Vuexで管理する状態を定義
  state: {
    count: 0,       // 1
    name: 'MouMou',
    password: 'hoge'
  },

  // getters : stateの値を取得する処理を定義
  //   引数のstateは上で宣言した状態管理オブジェクト
  getters: {
    count: state => state.count,        // 2
    name: state => state.name,          // 3
    password: state => state.password,  // 3
  },

  // mutations : stateの値を変更する処理を定義
  //   引数のstateは上で宣言した状態管理オブジェクト
  //   非同期処理に対応していない
  mutations: {
    setCount(state, newCount) {         // 4
      state.count = newCount
    },
    setName(state, newName) {           // 5
      state.name = newName
    },
    setPassword(state, newPassword) {   // 5
      state.password = newPassword
    }
  },
  // actions : mutationを呼び出す処理を定義
  //   非同期も対応している
  actions: {
    setCountAction({ commit }, newCount) {        // 6
      commit('setCount', newCount)
    },
    setNameAction({ commit }, newName) {          // 7
      commit('setName', newName)
    },
    setPasswordAction({ commit }, newPassword) {  // 7
      commit('setPassword', newPassword)
    },
  }
})
App.vue (他コンポーネントでも同様に記載できる)
<template>
  <div id="app">
    <!-- state -->
    <p>1. count = {{countDirect}}</p>
    <!-- getters -->
    <p>2. count = {{count}}</p>
    <p>3. name = {{name}}</p>
    <p>3. password = {{password}}</p>
    <!-- mutations -->
    <p><button @click="setCount">4. count = {{count}}</button></p>
    <p><button @click="setName('Qiita')">5. name = {{name}}</button></p>
    <p><button @click="setPassword('huga')">5. password = {{password}}</button></p>
    <!-- actions -->
    <p><button @click="setCountAction">6. count = {{count}}</button></p>
    <p><button @click="setNameAction('Vuex')">7. name = {{name}}</button></p>
    <p><button @click="setPasswordAction('huge')">7. password = {{password}}</button></p>
  </div>
</template>

<script>
// map系を使用する場合importする
import {mapGetters} from 'vuex'
import {mapMutations} from 'vuex'
import {mapActions} from 'vuex'

export default {
  computed: {
    // [1.state] 直接操作(非推奨)
    countDirect() {
      return this.$store.state.count
    },
    // [2.getters] stateの値を取得
    count() {
      return this.$store.getters.count
    },
    // [3.getters] 一括でgettersを設定
    ...mapGetters(['name','password']),
  },
  methods: {
    // [4.mutations] stateの値を変更
    setCount() {
      this.$store.commit("setCount", 1) // 第二引数はmutationに渡す値
    },
    // [5.mutations] 一括でmutationsを設定
    ...mapMutations(['setName','setPassword']) ,

    // [6.actions] mutationsを起動
    setCountAction() {
      this.$store.dispatch('setCountAction', 2) // 第二引数はmutationに渡す値
    },
    // [7.actions] 一括でactionsを設定
    ...mapActions(['setNameAction', 'setPasswordAction'])
  }
}
</script>

image.png
図. 表示画面

参考

2
7
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
2
7