LoginSignup
0
1

More than 3 years have passed since last update.

Vuexのstateをお手軽に扱えるようにするTips

Last updated at Posted at 2020-11-19

個人開発中に、Vuexのstateをお手軽に扱えるようにできたので参考までに共有します。
この方法を使うと、computedにいちいちgetterとsetterを記述しなくても、
this.xxxでstateへアクセスして、値を代入できるようになります!

1. mutationsにsetState関数を作る。

setState関数 … 任意のstateに任意の値をセットする処理。

store.js

export default new Vuex.Store({
  state: {
    xxx: null, // 例として「xxx」という名のstateを定義します。
  },
  mutations: {
    setState(state,nameValue){
      const stateName = nameValue[0];
      const stateValue = nameValue[1];
      state[stateName] = stateValue;
    }
  }
})

2. getとsetをreturnしてくれるstate関数を作る。

state.js

export const state = (stateName)=>({ // 注: アロー関数じゃないと正しく動きません。
  get(){
    return this.$store.state[stateName]
  },
  set(stateValue){
    this.$store.commit( 'setState', [ stateName, stateValue ] )
  }
})

3. computedにstate関数をセットする。

(正確には、state関数の返り値をセットする。)

component.vue

import {state} from 'state.js';
export default {
  computed: {
    xxx: state('xxx'),
  }
}

4. this.xxxでstateにアクセスできる。

component.vue

export default {
  computed: /*略*/,
  methods: {
    stateTest(){
      const getTest = this.xxx; // → this.$store.state.xxx の値が取得できる。
      this.xxx = 'setTest'; // → this.$store.commit( 'setState', [ 'xxx', 'setTest' ] ); が実行される。
    }
  }
}

補足. mapState関数もつくる。

Vuex公式のmapState関数のように、
配列やオブジェクトで一括定義したいと思うなら、mapState関数もつくります。

state.js

export const mapState = (stateNameList)=>{ // 注: アロー関数じゃないと正しく動きません。
  const argumentIsArray = Object.prototype.toString.call(stateNameList) === '[object Array]';
  const mapState = {};
  for(let i in stateNameList){
    const computedStateName = argumentIsArray ? stateNameList[i]: i;
    const storeStateName = stateNameList[i];
    mapState[computedStateName] = {
      get(){return this.$store.state[storeStateName]},
      set(v){this.$store.commit('setState',{[storeStateName]:v})}
    };
  }
  return mapState;
}
0
1
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
1