LoginSignup
5
18

More than 5 years have passed since last update.

vuexでのstate監視(watch)

Posted at

Vuexでstate監視の仕方

store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    foo: 1
  },
  getters: {
    getFoo: state => {
      return state.foo;
    }
  },
  mutations: {
    increment (state) {
      state.foo++;
    }
  },
  actions: {
    increment (context) {
      context.commit('increment');
    }
  }
});
foo.vue
<template>
    <div>{{ foo }}</div>
</template>
<script>
  export default {
    ...

    mounted: function () {
      // 1秒ごとにインクリメント
      setInterval(() => {
        this.$store.dispatch('increment')
      }, 1000);
    },

    computed: {
      foo() {
        return this.$store.getters.getFoo;
      },
    },

    watch: {
      foo (val, old) {
        console.log('watch', val);
      }
    }
  }
</script>

modulesを使った場合

store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import bar from './modules/bar'

Vue.use(Vuex);

export default new Vuex.Store({
  ...

  modules: {
    bar,
  }
});
modules/bar.js
export default {
  namespaced: true,
  state: {
    foo: 1
  },
  getters: {
    getFoo: state => {
      return state.foo;
    }
  },
  mutations: {
    increment (state) {
      state.foo++;
    }
  },
  actions: {
    increment (context) {
      context.commit('increment');
    }
  },
}
foo.vue
<template>
    <div>{{ foo }}</div>
</template>
<script>
  export default {
    ...

    mounted: function () {
      // 1秒ごとにインクリメント
      setInterval(() => {
        this.$store.dispatch('bar/increment') // namespaceで指定
      }, 1000);
    },

    computed: {
      foo() {
        return this.$store.getters['bar/getFoo']; // namespaceで指定
      },
    },

    watch: {
      foo (val, old) {
        console.log('watch', val);
      }
    }
  }
</script>
5
18
1

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
5
18