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>