vuex
vuex copied to clipboard
this is undefined inside the getters
What problem does this feature solve?
if (somehow) you can access to this inside getters then you could use plugins inside getters (as you can now in actions or mutations)
What does the proposed API look like?
I'm not sure how would i solve this, maybe this is a bug. The thing is that inside a getter you can use this.$myPlugin.whatever()
this in actions and mutations is originally private api. But it's now known by users since some Nuxt module use that. I think this in action may have valid use cases but still mutation should not access that as it should not make any side effects other than changing state.
IMO, getters should not allow to access to store instance via this because of the same reason as mutations.
If you think you have a valid use case for that, you should explain that concretely.
For example i have some service-plugins injected in the "this" with some methods to normalize some objects so i can call it from anywhere in the app (actions, components...)
class ItemNormalizer {
itemTransformer (item) {
return {
bar: item.bar.foo
foo: item.foo.toUpperCase()
}
}
}
//gets injected into this via nuxt plugin.
//then in some action...
...
someAction ({commit}, item) {
commit.(someMutation, this.$itemNormalizer.itemTransformer(item))
}
...
//in some component
...
computed: {
myItem () {
return this.$itemNormalizer.itemTransformer(this.$store.state.item)
}
}
...
// and I would like to use into getters
someGetter(state) {
return this.$itemNormalizer.itemTransformer(state.item)
}
// but here 'this' is undefined
Just ran into the same problem
Same here
Same here
I think we could consider adding this context to the getters as well. I don't think users should use it often, but some plugins might benefit from this feature. Simply to access the store instance since the plugin could inject some property to the store, then reference it inside getters like actions do in Nuxt.
Also, since having this context inside mutations and actions, it kinda makes thing more consistent.
There's a workaround to this if anyone viewing this comes across this problem: you could simply pass 'this' instance to getter as an argument while calling it :
checkGetter() {
return this.$store.getters.getSubject(this);
}
and then the getter would be:
export function getSubject() {
return function(that) {
// that.$axios.dosomething
// that.$someOtherPluginPerhaps
}
}
+1
There's a workaround to this if anyone viewing this comes across this problem: you could simply pass 'this' instance to getter as an argument while calling it :
checkGetter() { return this.$store.getters.getSubject(this); }and then the getter would be:
export function getSubject() { return function(that) { // that.$axios.dosomething // that.$someOtherPluginPerhaps } }
I assume this is wrong solution because in your example that will be pointed to vue component, instead of vuex.