数据加载

Data Loading

读取数据

import { emailApi } from '@/api/email.js'
export default {
  data () {
    returen {
      searchForm: {
        pageNum: 1,
	pageSize: 10
      }
    }
  },
  mounted () {
    this.load()
  },
  methods: {
    // 异步加载数据
    async load () {
      let res = await emailApi.emailPageQuery(this.searchForm)
      let datas = res.data
      console.log(datas)
    }
  }
}

API封装

import { postAxios, getAxios } from './method'
export const emailApi = {
  // 分页查询邮件
  emailPageQuery: data => {
    return postAxios('/email/page/query', data)
  },
  // 删除邮件
  emailDelete: id => {
    return getAxios('/email/delete/' + id)
  }
}

http.js

import Axios from 'axios';
import config from '@/config';
import { Message, Spin } from 'iview';
import Cookies from 'js-cookie';
import { TOKEN_KEY } from '@/lib/cookie';
// 之所以封装这个axios,是因为在一些请求中,无法上传信息,很尴尬,估计原因是继承的有问题,无法携带headers
export const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro;
export const socketBaseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.socketDev : config.baseUrl.socketPro;

let axios = Axios.create({
  baseURL: baseUrl,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
});
// 添加请求拦截器

axios
  .interceptors
  .request
  .use(function (config) {
    // 在发送请求之前做些什么
    config.headers['x-access-token'] = Cookies.get(TOKEN_KEY);
    return config;
  }, function (error) {
    // 对请求错误做些什么
    Spin.hide();
    return Promise.reject(error);
  });
// 添加响应拦截器
axios
  .interceptors
  .response
  .use((res) => {
    let { data } = res;
    if (data.code !== 1) {
      if (data.code === 1001) {
        Cookies.remove(TOKEN_KEY);
        localStorage.clear();
        window.location.href = window.location.pathname + '#/login';
        Message.error('未登录,或登录失效,请登录');
      } else if (data.code === 502) {
        window.location.href = window.location.pathname + '#/500';
      } else {
        Message.error(data.msg);
      }
      return Promise.reject(res);
    }
    return data;
  }, (error) => {
    Spin.hide();
    Message.error('服务内部错误');
    // 对响应错误做点什么
    return Promise.reject(error);
  });

export const postAxios = (url, data) => {
  return axios.post(url, data);
};
export const getAxios = (url, data) => {
  return axios.get(url, {
    params: data
  });
};


作者简介:
卓大, 1024创新实验室主任,混迹于各个技术,熟悉点java,略懂点前端。