首頁 > 軟體

vue3如何實現掛載並使用axios

2022-06-24 14:01:22

vue3掛載並使用axios

首先在main.js中引入axios並掛載到app.config.globalProperties上

axios組態檔放置./assets/js/axios

main.js

import {
    createApp
} from 'vue'
import App from './App.vue'
import './index.css'
import axios from './assets/js/axios';
const app = createApp(App);
app.use(router).use(ElementPlus).mount('#app')
app.config.globalProperties.$http = axios;

其次設定axios.js檔案

axios.js

import axios from "axios";
import qs from "qs";
import {
    ElMessageBox
} from 'element-plus';
// axios.defaults.baseURL = ''  //正式
axios.defaults.baseURL = 'http://localhost:8089' //測試
//post請求頭
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
//設定超時
axios.defaults.timeout = 10000;
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 => {
        ElMessageBox(JSON.stringify(error), '請求異常', {
            confirmButtonText: '確定',
            callback: action => {}
        });
    }
);
export default {
    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)
                })
        })
    }
};

最後在.vue中使用

通過getCurrentInstance拿到的ctx就有了$http可以呼叫

import {
  defineComponent,
  getCurrentInstance,
  reactive,
  toRefs,
} from "vue";
export default defineComponent({
  name: "demo",
  props: {},
  components: "",
  setup(props, context) {
    //參照全域性變數
    const { ctx } = getCurrentInstance();
    console.log(ctx);
    let state = reactive({
      ruleForm: {
        username: "fur",
        password: "123",
      }
    });
    function submitForm() {
      ctx.$http.post("/login/xxx", ruleForm).then((res) => {
        //請求成功
      });
    }
    return {
      ...toRefs(state),
      submitForm,
    };
  },
});

vue全域性掛載axios

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="app">
 
  </div>
 
  <script src="./node_modules/vue/dist/vue.js"></script>
  <script src="./node_modules/axios/dist/axios.js"></script>
  <script>
    // 全域性掛載axios:給Vue函數新增一個原型屬性$axios指向Axios
    // 好處是在vue範例或元件中不用重複參照Axios,直接用this.$axios就能執行axios方法
    Vue.prototype.$axios = axios;
    var App = {
      template: `
        <div><button @click="sendAjax">發請求</button></div>
      `,
      methods: {
        sendAjax() {
          console.log(this.$axios);
        }
      }
    };
    new Vue({
      el: '#app',
      data() {
        return {
 
        }
      },
      template: `
        <App />
      `,
      components: {
        App
      }
    });
  </script>
</body>
</html>

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com