Ammamon
Ammamon

Reputation: 497

How to access boot file configured axios from Quasar V2 Composition API setup function?

How to access boot file configured axios from Quasar V2 Composition API setup function, without importing axios in every file?

Since this.$axios can be used only for Options API, I tried to access through the context parameter of setup function.

Even though it works, context.root is now deprecated in Vue 3.

I do not want to import axios in every file as shown in the example at https://next.quasar.dev/quasar-cli/ajax-requests

For setup method access, I think it is still not implemented since mentioned as a TODO activity at https://next.quasar.dev/quasar-cli/boot-files#examples-of-appropriate-usage-of-boot-files

Similar to axios, usage of vue-i18n also from boot file is an issue for me.

 setup (props, context) {
         
    context.root.$axios({
    method: 'get',
        url: 'http://localhost:8080/storemgr/item/3',
      }).then((response: any) => {
          console.log(response)
      }).catch((error: any) => {
        console.log(error)
      })
...
}

Below is my axios boot file contents generated by Quasar V2 CLI


import axios, { AxiosInstance } from 'axios'
import { boot } from 'quasar/wrappers'

declare module 'vue/types/vue' {
  interface Vue {
    $axios: AxiosInstance;
  }
}

export default boot(({ Vue }) => {
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  Vue.prototype.$axios = axios
})

Upvotes: 6

Views: 4976

Answers (2)

Mahadi Hassan
Mahadi Hassan

Reputation: 310

For This worked

import {api} from 'boot/axios'

setup() {
    return{
        api.post('shop/', data, { #api imported that works in setup quasar
            headers: {
              Authorization: `token ${JSON.parse(localStorage.getItem("userData")).token}`,
              'Content-Type': 'multipart/form-data'
            },

            onUploadProgress: function (progressEvent) {
              console.log((progressEvent.loaded / progressEvent.total) * 100);
              dialog.update({
                message: `${(progressEvent.loaded / progressEvent.total) * 100}%`
              })
            }
          })
}
}

Upvotes: 1

Roland M
Roland M

Reputation: 95

The only other way I found is to use Provide/Inject. In my boot file, I use it like this:

export default boot(({ app }) => {
    app.config.globalProperties.$axios = axios
    app.provide('axios', app.config.globalProperties.$axios)
})

In any component:

setup() {
    const axios: AxiosInstance = inject('axios') as AxiosInstance
    [...]
}

In hindsight, I'm not quite sure if this is better than importing it.

Upvotes: 4

Related Questions