Reputation: 381
I want to access my states from a .js
file using mapState
in Vue.js.
I've tried
import { mapState } from 'vuex';
const foo = {
...mapState(['axios']),
};
foo.axios.get('...');
but it doesn't work. The error is
TypeError: foo.axios.get is not a function
What should I do to achieve that?
I have searched for other questions, but they access from store.state. ...
instead of using mapState
which I want.
Upvotes: 4
Views: 1887
Reputation: 29132
I'm not sure using mapState
is a good idea as it's very much intended to be used as a way to create computed properties on a component.
However, it can be made to work like this:
const foo = {
$store: store,
...mapState(['axios'])
};
foo.axios().get('...');
You can see the implementation of mapState
here:
https://github.com/vuejs/vuex/blob/dev/src/helpers.js#L7
Note that it relies on this.$store
to get a reference to the store. On a component this will be injected automatically but for your object it needs adding manually.
The other thing to note is that I'm having to invoke axios()
as a method. Computed properties on components are defined as functions but accessed as properties but that magic trick is performed internally by Vue. On a normal JavaScript object like this there is no such magic so we just have to call the function as a function. Other benefits of computed properties, such as the caching, will also be lost.
Upvotes: 4