為何捐款
API 瀏覽器
升級指南
NEW!
quasar.config 檔案
轉換為搭配 Webpack 的 CLI
瀏覽器相容性
支援 TypeScript
目錄結構
命令列表
CSS 預處理器
路由
延遲載入 - 代碼分割
處理資源
啟動檔案
預取功能
API 代理
處理 Webpack
處理 process.env
使用 Pinia 進行狀態管理
使用 Vuex 進行狀態管理
Linter
測試與稽核
開發行動應用程式
Ajax 請求
開放 Dev Server 給公眾
搭配 Webpack 的 Quasar CLI - @quasar/app-webpack
Ajax 請求

我們建議在專案初始化期間選取 Axios。

如果您在專案初始化期間沒有選取 Axios,那麼您應該建立一個新的啟動檔案 axios.js,內容如下:(您也可以在這裡為您的 axios 實例指定其他設定)

src/boot/axios.js

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

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

export default boot(({ 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 套件。

提示

如果您正在使用 Quasar CLI,請務必查看預取功能

在您的單文件組件方法中的用法如下所示。請注意,在下一個範例中,我們使用了 Quasar 的 Notify 外掛程式(透過 $q = useQuasar()$q.notify),您需要安裝它(請按照先前的連結)。

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 }
}

在 Vuex Actions 中使用,以全域方式為 axios 添加標頭(例如在身份驗證期間)

import { api } from 'boot/axios'

export function register ({ commit }, form) {
  return api.post('/auth/register', form)
    .then(response => {
      api.defaults.headers.common['Authorization'] = 'Bearer ' + response.data.token
      commit('login', {token: response.data.token, user: response.data.user})
    })
}

另請參閱 Axios 文件 以獲得更多資訊。