搭配 Webpack 的 Quasar CLI - @quasar/app-webpack
我們建議在專案初始化期間選取 Axios。
如果您在專案初始化期間沒有選取 Axios,那麼您應該建立一個新的啟動檔案 axios.js
,內容如下:(您也可以在這裡為您的 axios 實例指定其他設定)
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 }
content_paste
也請確保使用 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 }
}
content_paste
在 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})
})
}
content_paste
另請參閱 Axios 文件 以獲得更多資訊。