当前位置:   article > 正文

vue2版本+TS(typescript)+封装api_ts封装api

ts封装api

vue+TS(typescript)+封装api

1、在src下新建一个 utli文件夹 文件夹下新建一个request.ts文件,在此文件里写如如下代码

在这里插入图片描述

import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios"
//创建axsio 赋给常量service
 const service:AxiosInstance = axios.create({
   baseURL:'',
   timeout:100000
 });
// 添加请求拦截器
service.interceptors.request.use(function(config:AxiosRequestConfig):AxiosRequestConfig {//config是请求时的配置信息。
  // 在发送请求之前做些什么
  // 设置请求头 携带token
  const token:string | null = localStorage.getItem('token')
  if(token){
    config.headers = config.headers || {}
    config.headers['XXXX'] = token
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
// 添加响应拦截器
service.interceptors.response.use(function (response:AxiosResponse):AxiosResponse {//response参数是响应对象
  // 对响应数据做点什么
  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});
export default service

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

2、在src下新建一个api文件夹 在api文件夹下新建一个ts文件

在这里插入图片描述

import request from '../utli/request'

export const loginApi =(data:{passworld:string,username:string}):Promise<Ajax.AjaxRsp> => request.post('/login',data)


  • 1
  • 2
  • 3
  • 4
  • 5

3、在页面中写代码发请求
在这里插入图片描述

<template>
  <div class="loginBox">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="ruleForm.username"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="ruleForm.passworld"
          placeholder="请输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm()"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang='ts'>
import {Component, Vue, Ref} from 'vue-property-decorator'
import { ElForm } from "element-ui/types/form";
import {loginApi} from '@/api/login'
interface UserInfo{
  username:string,
  passworld:string
}
interface RulesObj  {
  required:boolean,
  message:string,
  trigger:string,
}
@Component({
  components:{}
})
export default class Login extends Vue{
  @Ref('ruleForm') readonly ruleFormRef!:ElForm
  ruleForm:UserInfo={username:"",passworld:""}
  rules:{username:Array<RulesObj>,passworld:Array<RulesObj>}={
    username:[
      {required:true,message:"用户不能为空",trigger:"blur"}
    ],
    passworld:[
      {required:true,message:"密码不能为空",trigger:"blur"}
    ]
  }
  submitForm(formName: string):void{
    this.ruleFormRef.validate(async(valid: boolean) => {
      if(valid){
        // 发送请求
        let res:Ajax.AjaxRsp = await loginApi({
          passworld:this.ruleForm.passworld,
          username:this.ruleForm.username
        })
        if(res.errno===0){
          //存token
        }else{
          this.$message.error(res.errmsg)
        }
      }
    })
  }
}

</script>

<style scoped>
.loginBox {
  width: 500px;
  margin: 50px auto;
}
</style>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84

ps: 上面代码中用到了一个Ajax.AjaxRsp
此处用到了命名空间
(1)在项目中找到shims-vue.d.ts文件 加上如下代码

  declare global{
    namespace Ajax{
      interface AjaxRsp{
        errno:number,
        errmsg:string,
        data:any
      }
    }
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

如图:
在这里插入图片描述
不用导出 在任何地方就可以使用了

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

闽ICP备14008679号