In the process of developing an application using Vue 3
, I have created an api
class specifically for handling API calls:
import axios from 'axios'
export default class {
/**
* Send GET Request
* @param {string} url
* @return {Promise}
*/
get(url) {
return new Promise((resolve, reject) => {
axios.get(url, {}).then(response => {
if (response.status === 200) {
return resolve(response);
}
}).catch((error) => {
return reject(error);
})
});
}
/**
* Send POST Request
* @param {string} url
* @param {object} payload Data object to send
* @return {Promise}
*/
post(url, payload) {
return new Promise((resolve, reject) => {
axios.post(url, payload, {}).then(response => {
if (response.status === 200) {
return resolve(response);
}
}).catch((error) => {
return reject(error);
})
});
}
/**
* Send FIND Request
* @param {string} url
* @return {Promise}
*/
find(url) {
return new Promise((resolve, reject) => {
axios.get(url, {}).then(response => {
if (response.status === 200) {
return resolve(response);
}
}).catch((error) => {
return reject(error);
})
});
}
}
To use the functions in this class within my Vue components, I imported the _api.js
file and included .provide('$api', apis)
in the createApp
function within the app.js
file:
import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/inertia-vue3';
import api from './Models/_api'
const apis = new api();
createInertiaApp({
resolve: (name) => require(`./Pages/${name}.vue`),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.mixin({ methods: { route } })
.provide('$api', apis)
.mount(el);
},
});
In one of my components, I am utilizing it as follows:
<template>
//HTML Files
</template>
export default {
data(){
return{
tableData:[],
}
},
methods:{
fetchData(){
this.$api.post('/api/user-data', {}).then(response=>{
if(response.status === 200)
{
this.tableData = response.data.data
}
});
}
},
created(){
this.fetchData();
},
}
</script>
However, when attempting to use this.$api
, an error is thrown:
TypeError: Cannot read properties of undefined (reading 'post')
The issue persists even after trying console.log(this.$api)
which returns undefined
In contrast, the following approach worked effectively in Vue 2:
Back when I was working with Vue 2
, everything functioned perfectly fine by simply initializing the class in app.js
and adding it to the prototype
.
Sample Vue 2 Code snippet from app.js
:
import { App, plugin } from '@inertiajs/inertia-vue'
import Vue from 'vue'
import api from './Models/_api'
const apis = new api();
Vue.prototype.$api = apis;
const el = document.getElementById('app')
new Vue({
store: store,
render: h => h(App, {
props: {
initialPage: JSON.parse(el.dataset.page),
resolveComponent: name => import(`NitsPages/${name}`).then(module => module.default),
},
}),
}).$mount(el)