当前位置:   article > 正文

axios在vue3+ts中的环境中使用_vue3+ts 中使用axios

vue3+ts 中使用axios

1、安装依赖:

命令行:vue ui  ;打开该项目,引入相应的axios和vue-axios

2、编写reauest.ts

  1. import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
  2. import {message, notification} from 'ant-design-vue';
  3. export class Request {
  4. public static axiosInstance: AxiosInstance;
  5. // constructor() {
  6. // // 创建axios实例
  7. // this.axiosInstance = axios.create({timeout: 1000 * 12});
  8. // // 初始化拦截器
  9. // this.initInterceptors();
  10. // }
  11. public static init() {
  12. // 创建axios实例
  13. this.axiosInstance = axios.create({
  14. baseURL: '/api',
  15. timeout: 6000
  16. });
  17. // 初始化拦截器
  18. this.initInterceptors();
  19. return axios;
  20. }
  21. // 为了让http.ts中获取初始化好的axios实例
  22. // public getInterceptors() {
  23. // return this.axiosInstance;
  24. // }
  25. // 初始化拦截器
  26. public static initInterceptors() {
  27. // 设置post请求头
  28. this.axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  29. /**
  30. * 请求拦截器
  31. * 每次请求前,如果存在token则在请求头中携带token
  32. */
  33. this.axiosInstance.interceptors.request.use(
  34. (config: AxiosRequestConfig) => {
  35. // const token = Vue.ls.get(ACCESS_TOKEN)
  36. // if (token) {
  37. // config.headers['Authorization'] = 'Bearer ' + token
  38. // }
  39. // 登录流程控制中,根据本地是否存在token判断用户的登录情况
  40. // 但是即使token存在,也有可能token是过期的,所以在每次的请求头中携带token
  41. // 后台根据携带的token判断用户的登录情况,并返回给我们对应的状态码
  42. // if (config.headers.isJwt) {
  43. const token = localStorage.getItem('ACCESS_TOKEN');
  44. if (token) {
  45. config.headers.Authorization = 'Bearer ' + token;
  46. }
  47. // }
  48. return config;
  49. },
  50. (error: any) => {
  51. console.log(error);
  52. },
  53. );
  54. // 响应拦截器
  55. this.axiosInstance.interceptors.response.use(
  56. // 请求成功
  57. (response: AxiosResponse) => {
  58. // if (res.headers.authorization) {
  59. // localStorage.setItem('id_token', res.headers.authorization);
  60. // } else {
  61. // if (res.data && res.data.token) {
  62. // localStorage.setItem('id_token', res.data.token);
  63. // }
  64. // }
  65. if (response.status === 200) {
  66. // return Promise.resolve(response.data);
  67. return response;
  68. } else {
  69. Request.errorHandle(response);
  70. // return Promise.reject(response.data);
  71. return response;
  72. }
  73. },
  74. // 请求失败
  75. (error: any) => {
  76. const {response} = error;
  77. if (response) {
  78. // 请求已发出,但是不在2xx的范围
  79. Request.errorHandle(response);
  80. return Promise.reject(response.data);
  81. } else {
  82. // 处理断网的情况
  83. // eg:请求超时或断网时,更新state的network状态
  84. // network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
  85. // 关于断网组件中的刷新重新获取数据,会在断网组件中说明
  86. message.warn('网络连接异常,请稍后再试!');
  87. }
  88. });
  89. }
  90. /**
  91. * http握手错误
  92. * @param res 响应回调,根据不同响应进行不同操作
  93. */
  94. private static errorHandle(res: any) {
  95. // 状态码判断
  96. switch (res.status) {
  97. case 401:
  98. break;
  99. case 403:
  100. break;
  101. case 404:
  102. message.warn('请求的资源不存在');
  103. break;
  104. default:
  105. message.warn('连接错误');
  106. }
  107. }
  108. }

3、main.ts中引入axios和request

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import router from './router'
  4. import store from './store'
  5. import Antd from 'ant-design-vue'
  6. import 'ant-design-vue/dist/antd.css'
  7. // import { HttpService } from "@/utils/http";
  8. // import { VueAxios } from './utils/request'
  9. // import axios from 'axios'
  10. import { Request } from '@/utils/request';
  11. import VueAxios from 'vue-axios'
  12. const app = createApp(App as any)
  13. // app.config.productionTip = false
  14. app
  15. .use(store)
  16. .use(router)
  17. .use(Antd)
  18. .use(VueAxios, Request.init())
  19. .mount('#app')

4、编写接口

  1. import { Request } from '@/utils/request';
  2. export function login (parameter: any) {
  3. return Request.axiosInstance({
  4. url: '/cxLogin',
  5. method: 'post',
  6. data: parameter
  7. })
  8. }

5、vue文件中使用

  1. <template>
  2. <div class="login-container">
  3. <div class="content">
  4. <a-card title="欢迎登陆CX工作流设计器" style="width: 100%;height: 100%">
  5. <a-form :model="loginForm" @submit="handleSubmit"><!--@submit.native.prevent-->
  6. <a-form-item>
  7. <a-input v-model:value="loginForm.account" placeholder="account" style="width: 350px" >
  8. <template #prefix><UserOutlined style="color:rgba(0,0,0,.25)"/></template>
  9. </a-input>
  10. </a-form-item>
  11. <a-form-item>
  12. <a-input v-model:value="loginForm.password" type="password" placeholder="Password" style="width: 350px">
  13. <template #prefix><LockOutlined style="color:rgba(0,0,0,.25)"/></template>
  14. </a-input>
  15. </a-form-item>
  16. <a-form-item>
  17. <a-button type="primary" html-type="submit" :disabled="loginForm.account === '' || loginForm.password === ''" style="width: 350px">
  18. 登陆
  19. </a-button>
  20. </a-form-item>
  21. </a-form>
  22. </a-card>
  23. </div>
  24. </div>
  25. </template>
  26. <script lang="ts">
  27. import '../../reset.less'
  28. import '../../global.css'
  29. import { defineComponent, reactive } from "vue";
  30. import { UserOutlined, LockOutlined } from '@ant-design/icons-vue';
  31. import { login } from '@/api/modular/auth'
  32. import { useRouter } from 'vue-router'
  33. export default defineComponent({
  34. name: "index",
  35. components: {
  36. UserOutlined,
  37. LockOutlined,
  38. },
  39. setup(){
  40. const loginForm = reactive({
  41. account: '',
  42. password:''
  43. })
  44. const router = useRouter()
  45. const handleSubmit = (e: Event)=> {
  46. const param = {
  47. account: loginForm.account,
  48. password: loginForm.password
  49. }
  50. login(param).then(response => {
  51. const res: any = response.data
  52. if(res.code === 200){
  53. localStorage.setItem('ACCESS_TOKEN', res.data);
  54. router.push("/flow")
  55. }
  56. })
  57. }
  58. return{
  59. loginForm,
  60. handleSubmit
  61. }
  62. }
  63. })
  64. </script>
  65. <style lang="less" scoped>
  66. /* 背景 */
  67. .login-container {
  68. position: absolute;
  69. width: 100%;
  70. height: 100%;
  71. background: url("../../assets/cool-background.png");
  72. .content {
  73. position: absolute;
  74. width:400px;
  75. height:300px;
  76. left:50%;
  77. top:50%;
  78. margin-left:-200px;
  79. margin-top:-150px;
  80. border-radius: 10px;
  81. background: #f6efef;
  82. box-shadow: 5px 5px 10px #626060,
  83. -2px -2px 2px #de18ff;
  84. }
  85. }
  86. </style>

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/285661
推荐阅读
相关标签
  

闽ICP备14008679号