Here is an example of a Vuex Store with a parameterized getter which I need to map onto the Vue instance to use within the template.
const store = new Vuex.Store({
state: {
lower: 5,
higher: 10,
unrelated: 3
},
getters: {
inRange: state => value => {
console.log('inRange run')
return (state.lower <= value) && (state.higher >= value)
}
},
mutations: {
reduceLower: state => state.lower--,
incrementUnrelated: state => state.unrelated++
}
})
new Vue({
el: '#app',
template: "<div>{{ inRange(4) }}, {{ unrelated }}</div>",
store,
computed: Object.assign(
Vuex.mapGetters(['inRange']),
Vuex.mapState(['unrelated'])
),
})
setTimeout(function() {
console.log('reduceLower')
store.commit('reduceLower')
setTimeout(function() {
console.log('incrementUnrelated')
store.commit('incrementUnrelated')
}, 3000);
}, 3000);
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex/dist/vuex.js"></script>
<div id="app"></div>
Firstly, this does appear to be valid, working code. However considering computed
is meant to be a cached set of computed properties, I'm curious about the behavior in this scenario, is there caching going on? If there isn't, is there a performance concern to consider? Even though the function does not cause any state change, should it be a method
?
Is this an anti-pattern? The example isn't a real one, but I do want to centralize logic in the store.
UPDATE
I have updated the example to illustrate that modifications to the underlying lower/higher
value upon which the inRange
getter is based, are indeed reactive for the Vue instance (despite not being mapped as state). I have also included an unrelated
value which is not part of the calculation, if the mapped getter were cached, modifying the unrelated value should not trigger the getter to be called again, however it does.
My conclusion is that there is no caching, thus this has poorer performance than a conventional computed property, however it is still functionally correct.
The question remains open as to whether there is any flaw in this pattern, or one available which performs better.