vue基础2:class

156 阅读1分钟

class

class是一个语法糖,其底层还是通过 构造函数 去创建的。所以它的绝大部分功能,ES5 都可以做到。新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

一个class的应用实例

封装一个axios 请求类

const DEFAULT_OPTIONS = {
  
  timeout: 30000,
  headers: {
    timestamp: new Date().getTime(),
    'Content-Type': 'application/json;chareset=UTF-8'
  }
}

const responseLog = (response) => {
  if (process.env.NODE_ENV === 'development') {
    const randomColor = `rgba(${Math.round(Math.random() * 255)},${Math.round(
      Math.random() * 255
    )},${Math.round(Math.random() * 255)})`
    console.log(
      '%c┍------------------------------------------------------------------┑',
      `color:${randomColor};`
    )
    console.log('| 请求地址:', response.config.url)
    console.log('| 请求参数:', response.config.data ? JSON.parse(response.config.data) : {})
    console.log('| 返回数据:', response.data)
    console.log(
      '%c┕------------------------------------------------------------------┙',
      `color:${randomColor};`
    )
  }
}

const instance = axios.create(DEFAULT_OPTIONS)

instance.interceptors.request.use(
  (config) => {
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true
    })
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  (error) => {
    Toast.clear()
    Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    Toast.clear()
    responseLog(response)
    const code = response.data.code
    const msg = RESTFUL_ERROR_CODE_MAP[code]
    if (msg) {
      Toast(response.data.message || msg)
      if (code === 401) {
        Dialog.confirm({
          message: response.data.message || msg
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(response.data.message || msg))
    } else {
      return response
    }
  },
  (thrown) => {
    Toast(thrown.message || 'Error')
    setTimeout(() => {
      Toast.clear()
    }, 500)
    return Promise.reject(thrown)
  }
)

export default async function(options) {
  const { url } = options
  const requestOptions = Object.assign({}, options)

  try {
    const { data, data: { errno, errmsg }} = await instance.request(requestOptions)
    if (errno) {
      errorReport(url, errmsg, requestOptions, data)
      throw new Error(errmsg)
    }
    return data
  } catch (err) {
    errorReport(url, err, requestOptions)
    throw err
  }
}

import service from '@/core/services/http'

export class Request {
  instance

  static getInstance() {
    if (!this.instance) {
      this.instance = new Request()
    }
    return this.instance
  }

  async post(options = {}) {
    const { data } = await service({
      method: 'post',
      ...options
    })
    return data
  }
  async delete(options = {}) {
    const { data } = await service({
      method: 'delete',
      ...options
    })
    return data
  }

  async put(options = {}) {
    const { data } = await service({
      method: 'put',
      ...options
    })
    return data
  }

  async get(options = {}) {
    const { data } = await service({
      method: 'get',
      ...options
    })
    return data
  }
}

定义类的时候,前面不需要加 function, 而且方法之间不需要逗号分隔,加了会报错。

使用类方法

import {Request} from '@/core/services/http/request'
//获取实例,调用getInstance静态方法构建实例
const HTTPRequest = Request.getInstance()
//调用实例中的方法
HTTPRequest.post({url:xxxx, data:{name:username})