网络编程
位置:首页>> 网络编程>> JavaScript>> vue3如何实现挂载并使用axios

vue3如何实现挂载并使用axios

作者:furfur-jiang  发布时间:2023-07-02 16:46:06 

标签:vue3,挂载,axios

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,
   };
 },
});

vue3如何实现挂载并使用axios

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>

vue3如何实现挂载并使用axios

来源:https://jiangmq.blog.csdn.net/article/details/116210864

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com