I'd like to watch the store value, but the error: [vuex] store.watch only accept a function.
I referred to this site.
https://codepen.io/CodinCat/pen/PpNvYr
If I have more than one store, how do I watch it?
index.js
'use strict';
import Vue from 'vue';
import Vuex from 'vuex';
import {test1Store} from './modules/test1.js';
import {test2Store} from './modules/test2.js';
Vue.use (Vuex);
export store=newVuex.Store({
modules: {
test1: test1 Store,
test2—tes21 Store,
}
});
test1.js
'use strict';
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use (Vuex);
export const checkerStore={
namespaced:true,
state: {
count:1
},
getters: {
getCount(state){
return state.count;
}
}
};
export default {test1};
test.vue
<template>
{{ $store.state.count}}
</template>
<script>
import {store} from './store/index.js';
export default {
data:function(){
US>return{
}
},
store:store,
methods: {
},
mounted() {
setInterval()=>{this.$store.state.count++},1000);
This.$store.watch(this.$store.getters['test1/getCount', n=>{
console.log ('watched:',n)
})
}
}
}
</script>
If you just want to log, I think you can do it with plugin.
https://codepen.io/isuke/pen/jxgdVQ
I wrote it here.
If you could write down what you want to do in more detail, I might be able to teach you a better way.
const logger=store=>{
store.subscribe(mutation, state)=>{
console.log('watched:'+state.test1.n)
})
}
conststore=newVuex.Store({
modules: {
test1: {
state: {
n:1
},
mutations: {
increment(state) {state.n++}
},
getters: {
getN(state) {state.n}
}
}
},
plugins: [logger]
})
new Vue({
el: '#app',
store,
methods: {
up(){
This.$store.commit('increment')
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.8/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.1.1/vuex.js"></script>
<divid="app">
<button@click="up">click</button>
{{ $store.state.test1.n}}
</div>
© 2024 OneMinuteCode. All rights reserved.