vue-element-adminvue的使用技巧

api的映射,axios全局注册

2020-06-30  本文已影响0人  johnnie_wang

之前程序员的写法

image.png

例 xxxx.ts

// 先引入
import request from '@/utils/request'


/**
* 添加点位
* @param position_name 位置名称
* @param is_enable 状态 1有效0无效
*/
export const devicePositionAdd = (param: any) =>
 request({
   url: '/device/business/device/devicePositionAdd',
   method: 'post',
   data: param
 })
 
···

缺点:

     // api文件
     import request from '@/utils/request'

     export const ··· = (param: any) =>
         request({
           url: ' ··· ',
           method: 'post',
           data: param
         })
      
     ···



     
     // 组件页面
     import { projectList, item, stadiumList ··· } from '@/api/stadium/data'
     import { couponApi ··· } from '@/api/business/coupon'

     ···



以上代码 重复太多 

我的写法

  1. 首先是 main.ts全局 注册 axios
import request from '@/utils/request'

// 在这里挂载全局 api request
  declare module 'vue/types/vue' {
    interface Vue {
      $request: any
    }
  }

  Vue.prototype.$request = function(url:string, params:object) {
    return request({
      url: url,
      method: 'post',
      data: params
    })
  }
  1. 在组件中使用 (两种方法)

第一种


/*
* @api 接口
* @params 参数
*/
this.$request(api, params).then(res => {
    ···
  }).catch(err => {
     ···
  })

第二种

async 
 

const res = await this.$request(api, param)

...
  1. api 映射

[图片上传失败...(image-75c14-1593489367921)]

一个文件解决 整个系统的api, 不会造成代码冗余的情况

  1. api 映射写法的规范
a. 大写 
b. 下划线
c. GET_LIST  // 获取数据
d. ADD_DATA  // 新增数据
e. DEL_DATA  // 删除数据
f. UPDATE_DATA // 修改数据
g. GET_INFO  // 查询数据
h. 如果里面还有form ,则 
  FORM: {
     GET_INFO: 
     ADD_DATA:
     ···
  }
  
例 2.的图片
  1. 配合mixins的使用
a. 首先组件引入

```

import { Vue, Component, Mixins } from 'vue-property-decorator'

// 引入api
import { SIGNUP } from '@/api/apiList'


// 引入混入 
import { List } from '@/mixins/list'


export default class extends Mixins(List) {

public URLOBJ = SIGNUP

}

```


b. list.ts 混入

例   

```

export class List extends Mixins(RouterPush) {
     
  /**
   * @description 混入中定义的api , 会被组件页面中的URLOBJ的数据覆盖
   * 这个页面使用了这三个接口,typescript的语法规范中, 必须在本页面声明,才可以调用,
   * 否则会报undefined ,目前没有想到好的解决办法
   */   
   
  public URLOBJ = {
    GET_LIST: '',
    DEL_DATA: '',
    UPDATE_DATA: ''
  }

  public formFilter = {
  }

  public listLoading = false
  public dataList = []
  public count = 0

  // 初始化 created 里面的方法会和组件的created方法合并, 并且 先执行
  created() {
    this.handleFilter()
  }

  /**
   * @description 列表过滤方法
   */
  @Watch('formFilter', { deep: true })
  public handleFilter() {
    this.listLoading = true
    
    //  这里直接使用 this.URLOBJ.GET_LIST 
    //  每个不同的组件可以引用不同的api , 实现一套方法, 多组件使用
        
    // this.formFilter 也是相同原理 
    // 每个页面 定义不同的过滤字段, 实现一套方法, 多组件使用      

    this.$request(this.URLOBJ.GET_LIST, this.formFilter).then(res => {
      this.listLoading = false
      if (res.code === 200) {
        this.dataList = res.data.list
        this.count = res.data.count
      }
    })
  }
  
  ···
  
}

```

优点:

上一篇 下一篇

猜你喜欢

热点阅读