Vuex模块可以监视其他模块的状态,并因此触发操作吗?
例如,让我们考虑以下情况:
store.js
import time from './store/time' ;
import position from './store/position' ;
const store = new Vuex.Store
(
{
modules:
{
time,
position
}
}
) ;
store/time.js
export default
{
namespaced: true,
state:
{
time: new Date()
},
getters:
{
time: (aState) => aState.time
},
mutations:
{
setTime (aState, aTime)
{
aState.time = aTime ;
}
}
} ;
store/position.js
export default
{
namespaced: true,
state:
{
positions: {}
},
getters:
{
positions: aState => aState.positions
},
mutations:
{
setPositions (aState, aPositionArray)
{
aState.positions = aPositionArray ;
}
},
actions:
{
fetchPositionsAtTime ({ dispatch, commit, rootGetters }, { time })
{
// Fetch positions at given time from the server
// commit('setPositions', ...)
}
}
} ;
理想情况下,我希望位置模块能够观察时间模块,并在时间状态发生变化时立即重新获取位置(即触发fetchPositionsAtTime
)。
当然,我可以在setTime
突变中添加一个调度以触发位置模块操作,但我相信反过来(即观看)会更优雅(因为更多模块可能需要时间) )。
对此有何解决方案? (当然不使用Vue Component
,这就是重点)
答案 0 :(得分:10)
您可以使用商店实例的watch
方法观看time
状态,然后在fetchPositionsAtTime
值发生变化时发送time
操作:
store.watch((state) => state.time.time, (val) => {
store.dispatch('position/fetchPositionsAtTime', { time: val })
});
如果你不想直接观看州,你也可以像这样看一个吸气鬼:
store.watch((state, getters) => getters['time/time'], (val) => {
store.dispatch('position/fetchPositionsAtTime', { time: val })
});
Here's a link to the api documentation for Vuex.Store instances.
以下是一个例子:
const time = {
namespaced: true,
state: {
time: new Date()
},
getters: {
time: (aState) => aState.time
},
mutations: {
setTime (aState, aTime) {
aState.time = aTime ;
}
}
};
const position = {
namespaced: true,
state: {
positions: {}
},
getters: {
positions: aState => aState.positions
},
mutations: {
setPositions (aState, aPositionArray) {
aState.positions = aPositionArray ;
}
},
actions: {
fetchPositionsAtTime ({ dispatch, commit, rootGetters }, { time }) {
let value = rootGetters['position/positions'].value || 0;
commit('setPositions', { value: ++value });
}
}
};
const store = new Vuex.Store({
modules: { time, position }
});
store.watch((state) => state.time.time, (val) => {
store.dispatch('position/fetchPositionsAtTime', { time: val })
});
new Vue({
el: '#app',
store,
methods: {
setTime() {
this.$store.commit('time/setTime', new Date());
}
}
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
time: {{ $store.getters['time/time'] }}
<br>
position: {{ $store.getters['position/positions'] }}
<br>
<button @click="setTime">Change time</button>
</div>
&#13;