I'm still getting the hang of Typescript, but I'm facing some challenges with it when using Vuex/Axios.
Current setup includes: Vue CLI app, Vue 2, Vuex 3, Axios, Typescript
At a high level, I have a custom Axios instance where I configure the baseURL, interceptors, timeout settings, etc. I import Axios and then use axios.create()
to customize my settings.
My goal is to access this Axios instance from any component or the Vuex store using something like this.$api.get()
Currently, I have a file dedicated to my Axios instance:
import Vue from 'vue';
import axios from 'axios';
const $api = axios.create(
{
baseURL: 'https://myapi.com',
headers: {
...
},
timeout: 20000,
timeoutErrorMessage: 'timeout',
...
},
);
Vue.prototype.$api = $api;
In my Vuex store actions store/index.ts
export default new Vuex.Store({
...
actions: {
async fetchUser({ commit }): Promise<void> {
const path = '/me';
const user = await this.$api.get(path);
commit('setUser', user);
},
}
});
Then in my main.ts file:
import Vue from 'vue';
import store from './store';
import IndexPage from './pages/index.vue';
require('./plugins/api');
Vue.config.productionTip = false;
new Vue({
store,
render: (h) => h(IndexPage),
}).$mount('#app');
However, I keep encountering errors like:
Property '$api' does not exist on type 'Store<{ user: User; courses: Course[]; }>'.
I've attempted to use the Vue-axios npm package and access the API through Vue.$api.get()
Property '$api' does not exist on type 'VueConstructor