vue3使用axios 封裝使用
阿新 • • 發佈:2021-10-08
首先先下載
npm install axios --save
npm install qs --save
在專案中建立axios.js
import axios from "axios"; import qs from "qs"; // axios.defaults.baseURL = '' //正式 axios.defaults.baseURL = 'http://localhost:3000' //測試 //post請求頭 axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"; //允許跨域攜帶cookie資訊 axios.defaults.withCredentials = true; //設定超時 axios.defaults.timeout = 15000; axios.interceptors.request.use( config => { return config; }, error => { return Promise.reject(error); } ); axios.interceptors.response.use( response => { if (response.status == 200) { return Promise.resolve(response); } else { return Promise.reject(response); } }, error => { alert(JSON.stringify(error), '請求異常', { confirmButtonText: '確定', callback: (action) => { console.log(action) } }); } ); export default { /** * @param {String} url * @param {Object} data * @returns Promise */ post(url, data) { return new Promise((resolve, reject) => { axios({ method: 'post', url, data: qs.stringify(data), }) .then(res => { resolve(res.data) }) .catch(err => { reject(err) }); }) }, get(url, data) { return new Promise((resolve, reject) => { axios({ method: 'get', url, params: data, }) .then(res => { resolve(res.data) }) .catch(err => { reject(err) }) }) } };
在main.js中
import axios from './util/axios';
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App);
app.use(store)
.use(router)
.mount('#app')
app.config.globalProperties.$axios = axios;
在元件中直接使用
import {useStore} from 'vuex' import { ref, reactive, getCurrentInstance, onMounted, defineComponent } from "vue" export default defineComponent ({ name: 'Home', setup( props, context) { const homeStore = new useStore(); //使用useStore 例項化store const { proxy } = getCurrentInstance(); //來獲取全域性 globalProperties 中配置的資訊 //dom掛載後 onMounted(() => { sendHttp(); }); //傳送驗證碼 get同理 const sendHttp = () => { proxy.$axios .post("/captcha/sent", { phone: 12345678912, }) .then((res) => { //請求成功 console.log(res) }) .catch( err => { console.log(err) }) } return { sendHttp } } })
封裝api使用
import axios from "../util/axios";
let {get, post } = axios
//傳送驗證碼
export const sendCaptcha = data => get("/captcha/sent",data)
//驗證驗證碼
export const verifyCaptcha = data => post("/captcha/verify",data)
//註冊(修改密碼)
export const register = data => post("/register/cellphone",data)
在組建中呼叫api
import { ref,getCurrentInstance} from "vue" import { sendCaptcha} from "../api/login" export default { setup() { const captcha = ref('') //驗證碼 const phone =ref('')// 手機號碼 const {proxy} = getCurrentInstance() //獲取全域性配置資訊 const onSubmit = () => { proxy.$axios .post("/captcha/sent", { phone: 18700880154, }) .then((res) => { //請求成功 console.log(res) }) .catch( err => { console.log(err) }) }; return { captcha, phone, onSubmit } }, methods:{ sendCaptcha(){ sendCaptcha({phone:this.phone}).then((res) =>{ console.log(res) }) } } }