API 浏览器
Quasar CLI with Webpack - @quasar/app-webpack
Ajax 请求

我们建议在项目初始化期间选择 Axios。

¥We recommend selecting Axios during project initialization.

如果你在项目初始化期间未选择 Axios,则应创建一个新的启动文件 axios.js,如下所示:(你还可以在此处为你的 axios 实例指定其他设置)

¥If you haven’t selected Axios during the project initialization then you should create a new boot file axios.js that looks like this: (Here you can also specify additional settings for your axios instance)

src/boot/axios.js

import { defineBoot } from '#q-app/wrappers'
import axios from 'axios'

const api = axios.create({ baseURL: 'https://api.example.com' })

export default defineBoot(({ app }) => {
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$api = api
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
})

export { axios, api }

还要确保通过 yarn/npm 安装 axios 包。

¥Also make sure to yarn/npm install the axios package.

提示

如果你使用 Quasar CLI,请务必查看 预取功能

¥Be sure to check out Prefetch Feature if you are using Quasar CLI.

在单文件组件方法中的用法如下所示。请注意,在下一个示例中,我们将使用 Quasar 的 Notify 插件(到 $q = useQuasar()$q.notify),你需要安装它们(请点击之前的链接)。

¥Usage in your single file components methods will be like below. Notice that in the next example we’re using the Quasar’s Notify plugin (through $q = useQuasar() and $q.notify) which you’ll need to install (follow the link earlier).

import { ref } from 'vue'
import { api } from 'boot/axios'
import { useQuasar } from 'quasar'

setup () {
  const $q = useQuasar()
  const data = ref(null)

  function loadData () {
    api.get('/api/backend')
      .then((response) => {
        data.value = response.data
      })
      .catch(() => {
        $q.notify({
          color: 'negative',
          position: 'top',
          message: 'Loading failed',
          icon: 'report_problem'
        })
      })
  }

  return { data, loadData }
}

在 Pinia Actions 中全局向 axios 添加标头(例如在身份验证期间)的用法:

¥Usage in Pinia Actions for globally adding headers to axios (such as during authentication):

import { api } from 'boot/axios'

export const useAuthStore = defineStore('auth', {
  actions: {
    register (form) {
      return api.post('/auth/register', form)
        .then(response => {
          api.defaults.headers.common['Authorization'] = 'Bearer ' + response.data.token
          // do something with { token: response.data.token, user: response.data.user }
        })
  }
})

另请参阅 Axios 文档 了解更多信息。

¥Also look at Axios docs for more information.