如何在Vue.js和Vuex中多看两个store?
How to watch two more stores in Vue.js and Vuex?
我正在使用 Vue.js 和 Vuex。
我想要 watch
store
的值(我将在本 post 的最后分享我的示例代码)。
但是我遇到了错误"Error: [vuex] store.watch only accepts a function."
在这个网站上,我找到了如何使用 "single" 商店。
https://codepen.io/CodinCat/pen/PpNvYr
但是,就我而言,我想使用 "two" 商店。
你有什么办法解决这个问题吗?
●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 const store = new Vuex.Store({
modules: {
test1: test1Store,
test2: tes21Store,
}
});
●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.couunt }}
</template>
<script>
import {store} from './store/index.js';
export default {
data: function () {
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>
你得到那个错误是因为在你的示例代码中,你传递给 watch
的第一个参数,正如错误所暗示的那样,不是 function
.
该参数实际上是通过 Vue 在后台使用本机 JavaScript 调用 Object.defineProperty
实现的,因此执行 store.getters['test1/getCount']
的结果实际上是 number
.
我认为不建议在像你这样的场景中使用 watch
,但如果你坚持,你可以通过提供替代参数形式来访问 count
,例如:
this.$store.watch((state, getters) => getters['test1/getCount'], n => { ... })
我正在使用 Vue.js 和 Vuex。
我想要 watch
store
的值(我将在本 post 的最后分享我的示例代码)。
但是我遇到了错误"Error: [vuex] store.watch only accepts a function."
在这个网站上,我找到了如何使用 "single" 商店。 https://codepen.io/CodinCat/pen/PpNvYr
但是,就我而言,我想使用 "two" 商店。 你有什么办法解决这个问题吗?
●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 const store = new Vuex.Store({
modules: {
test1: test1Store,
test2: tes21Store,
}
});
●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.couunt }}
</template>
<script>
import {store} from './store/index.js';
export default {
data: function () {
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>
你得到那个错误是因为在你的示例代码中,你传递给 watch
的第一个参数,正如错误所暗示的那样,不是 function
.
该参数实际上是通过 Vue 在后台使用本机 JavaScript 调用 Object.defineProperty
实现的,因此执行 store.getters['test1/getCount']
的结果实际上是 number
.
我认为不建议在像你这样的场景中使用 watch
,但如果你坚持,你可以通过提供替代参数形式来访问 count
,例如:
this.$store.watch((state, getters) => getters['test1/getCount'], n => { ... })