创建httpService.js 文件
import axios from 'axios'; import { Loading , Message } from 'element-ui'; import { Vuevm } from '../main'; window.Vuevm = Vuevm; const BASE_URL = process.env.BASE_API; //域名路径 const formatParams = (data)=>{ let arr = []; for (let name in data) { arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name])); } return arr.join("&"); } axios.defaults.timeout = 15000; //超时时间 export const httpService = (url,params,method,loading=true) => { if(loading) { var loadingInstance = Loading.service({ lock: true, text: '加载中', spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)" }); } if(method === 'post') { return new Promise((resolve, reject) => { axios.post(BASE_URL+url, params,{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(data=>{ if(loading) loadingInstance.close(); resolve(data.data); }).catch(error=>{ reject(error); Message.error('网络不给力'); if(loading) loadingInstance.close(); }); }) } else { return new Promise((resolve, reject) => { axios.get(BASE_URL+url+'?'+formatParams(params)).then(data=>{ resolve(data.data); if(loading) loadingInstance.close(); }).catch(error=>{ Message.error('网络不给力'); if(loading) loadingInstance.close(); reject(error); }); }) } }
创建 使用的接口API 文件 api.js
import { httpService } from './httpService'; /** * @name 医院列表 * @param {*} params */ export const hospitalList = (params) =>{ return httpService('hospital/list',params,'get'); } /** * @name 医院详情 * @param {*} params */ export const hospitalDetail = (params) =>{ return httpService('/hospital/detail',params,'get'); }
页面引用 使用 index.vue
<template> <div class="commodit"> </div> </template> <script> import { hospitalList, hospitalDetail } from "@/api/hospital"; export default { name: "Commodit", components: { }, data() { return { tableData: [], }; }, created() { this.hospitalList() }, methods: { //获取 医院列表 async hospitalList() { var data = { hospitalName: '', pageSize: 10, pageNum: 1 }; const listData = await hospitalList(data); console.log(listData) if( listData.code==0 ){ this.tableData = listData.data.records } }, } }; </script> <style scoped lang="scss"> @import "../../filters/css/all.css"; .commodit { } </style>