- 控制臺安裝axios
npm install axios --save
- 創建檔案:src/axios/index.js,通過Promise封裝axios
import axios from 'axios';
axios.defaults.baseURL='/api' //此路徑為配置代理服務器時的代理路徑
export default {
get(url, data, responseType) { // url: 介面;路徑;data: 請求引數;responseType:相應的資料型別,不傳默認為json
return new Promise((resolve, reject) => {
axios({
method: 'get',
url,
data,
headers: {
Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8',
withCredentials: true,
},
//默認json格式,如果是下載檔案,需要傳 responseType:'blob'
responseType: (responseType == null || responseType == '') ? 'json' : responseType
}).then(response => {
if (response.status == 200) {
//根據實際情況進行更改
resolve(response)
} else {
reject(response)
}
})
})
},
post(url, data, responseType) { // url: 介面;路徑;data: 請求引數;responseType:相應的資料型別,不傳默認為json
return new Promise((resolve, reject) => {
axios({
method: 'post',
url,
data,
headers: {
Accept: 'application/json', 'Content-Type': 'application/json; charset=utf-8',
withCredentials: true,
},
//默認json格式,如果是下載檔案,需要傳 responseType:'blob'
responseType: (responseType == null || responseType == '') ? 'json' : responseType
}).then(response => {
if (response.status == 200) {
//根據實際情況進行更改
resolve(response)
} else {
reject(response)
}
})
})
}
}
- 創建組態檔:專案根目錄/vue.config.js(和src同級),配置代理解決跨域
module.exports = {
publicPath : '/', //基本路徑
outputDir : 'dist', //打包的包檔案名
assetsDir : 'static', //css、js、img靜態資源存放檔案夾
lintOnSave : false, //是否在保存的時候使用 `eslint-loader` 進行檢查,默認true
runtimeCompiler : false, //是否使用包含運行時編譯器的 Vue 構建版本,默認false
productionSourceMap : false,//生產環境不需要 source map,加速生產環境構建,默認true
devServer: { //webpack-dev-server配置
host : 'localhost',
port : 8080, //配置本專案運行埠
proxy: { //配置代理服務器來解決跨域問題
'/api': {
target: 'http://localhost:3000', //配置要替換的后臺介面地址
changOrigin: true, //配置允許改變Origin
pathRewrite: {
'^/api': ''
}
},
}
},
}
- .main.js檔案中匯入封裝好的axios,并進行全域掛載
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
const app = createApp(App)
app.use(store)
app.use(router)
app.mount('#app')
// 匯入封裝好的axios并掛載到Vue全域屬性上
import Axios from './axios/index.js'
app.config.globalProperties.$axios = Axios
- 組件中使用axios進行網路請求
<template>
<div>
<p></p>
</div>
</template>
<script>
import { defineComponent, getCurrentInstance, onMounted } from 'vue'
export default defineComponent({
name: '',
setup(){
const { ctx } = getCurrentInstance() // 獲取背景關系物件
onMounted(() => {
ctx.$axios.post('/playlist/hot', {}) // 網路請求
.then(result => {
console.log(result)
}).catch(() => { /* */ })
})
return {}
}
})
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/259261.html
標籤:其他
上一篇:52-Android之內置應用
下一篇:c++讀入方式歸納
