返回

Vue基础配置

main.js

// main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui'
import './directive/index.js'
import './filter/index.js'
import {
	Message
} from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css'
import 'element-ui/lib/theme-chalk/display.css'
import './assets/styles/reset.css'
import './assets/styles/border.css'
import './assets/styles/iconfont.css'
import App from './App'
import router from './router'
import axios from '../config/http'
import qs from 'qs';
import apiConfig from '../config/api.config'
import store from './store/store'

Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.prototype.$http = axios
Vue.prototype.$baseUrl = apiConfig.baseUrl
// Vue.prototype.$qs = qs;
axios.defaults.baseURL = apiConfig.baseUrl


/* eslint-disable no-new */
new Vue({
	el: '#app',
	router,
	store,
	components: {
		App
	},
	template: '<App/>'
})

filter

// filter/index.js
import Vue from 'vue'
import { formatDate } from '../assets/js/date.js'

Vue.filter('priceFloat', function(value) {
	value = value.toString();
	var result = Number(value).toFixed(2);
	return result;
})

Vue.filter('shortString', function(value) {
	value = value.toString();
	if (value.length > 20) {
		value = value.substr(0, 20).concat('...');
	}
	return value;
})

Vue.filter('propTime', function(value) {
	let time = new Date(value)
	return formatDate(time, 'yyyy-MM-dd hh:mm:ss')
})

Vue.filter('formatTime', function(value) {
	// let time = new Date(value)
	// return formatDate(time, 'yyyy-MM-dd hh:mm:ss')
	let now = new Date().getTime()
	let differ = (now - value) / 1000 //转化成秒
	if (differ < 60) {
		return Math.floor(differ) + ' 秒前'
	} else if (differ / 60 < 60) {
		return Math.floor(differ / 60) + ' 分钟前'
	} else if (differ / 3600 < 24) {
		return Math.floor(differ / 3600) + ' 小时前'
	} else if (differ / 3600 / 24 < 30) {
		return Math.floor(differ / 3600 / 24) + ' 天前'
	} else {
		let time = new Date(value)
		return formatDate(time, 'yyyy-MM-dd')
	}
})

directive

// directive/index.js
import Vue from 'vue'

Vue.directive('focus', {
	inserted: function(el) {
		el.querySelector('input').focus()
	}
})

Vue.directive('noMoreClick', {
	inserted(el, binding) {
		el.addEventListener('click', e => {
			// el.classList.add('is-disabled');
			el.disabled = true;
			setTimeout(() => {
				el.disabled = false;
				// el.classList.remove('is-disabled');
			}, 3000)
		})
	}
})

axios

// axios/domain.js
/**
 * 接口域名的管理
 */

const domainMap = new Map(
  [
    "production", // 生产环境接口
    {
      v1: "https://xxxx111111.com/api/v1",
      v2: "http://xxxxx22222.com/api/v2"
    }
  ],
  [
    "development", // 开发环境接口
    {
      v1: "https://xxxx111111.com/api/v1",
      v2: "http://xxxxx22222.com/api/v2"
    }
  ]
);

const base = domainMap.get(process.env.NODE_ENV);

export default base.v1;

// axios/http.js
/**
 * axios封装
 * 请求拦截、响应拦截、错误统一处理
 */
import axios from "axios";
import router from "../router";
import store from "../store/store";
import { Message } from "element-ui";
import qs from 'qs'

/**
 * 提示函数
 * 禁止点击蒙层、显示一秒后关闭
 */
const tip = msg => {
  Message({
    showClose: true,
    message: msg,
    type: "error"
  });
};

/**
 * 跳转登录页
 * 携带当前页面路由,以期在登录页面完成登录后返回当前页面
 */
const toLogin = () => {
  router.replace({
    path: "/login",
    query: {
      redirect: router.currentRoute.fullPath
    }
  });
};

/**
 * 请求失败后的错误统一处理
 * @param {Number} status 请求失败的状态码
 */
const errorHandle = (status, other) => {
  // 状态码判断
  switch (status) {
    // 401: 未登录状态,跳转登录页
    case 401:
      toLogin();
      break;
    // 403 token过期
    // 清除token并跳转登录页
    case 403:
      tip("登录过期,请重新登录");
      localStorage.removeItem("token");
      store.commit("loginSuccess", null);
      setTimeout(() => {
        toLogin();
      }, 1000);
      break;
    // 404请求不存在
    case 404:
      tip("请求的资源不存在");
      break;
    default:
      console.log(other);
  }
};

// 创建axios实例
var instance = axios.create({
  baseURL : '/api/api',
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  },
  // 允许改变发送到服务端的数,只适用于put、post、patch、delete
  transformRequest: [
    function(data, headers) {
      return headers.post["Content-Type"] ===
        "application/x-www-form-urlencoded"
        ? qs.stringify(data)
        : data;
    }
  ],
  timeout: 5000
});
// 设置post请求头

/**
 * 请求拦截器
 * 每次请求前,如果存在token则在请求头中携带token
 */

instance.interceptors.request.use(
  config => {
    // 登录流程控制中,根据本地是否存在token判断用户的登录情况
    // 但是即使token存在,也有可能token是过期的,所以在每次的请求头中携带token
    // 后台根据携带的token判断用户的登录情况,并返回给我们对应的状态码
    // 而后我们可以在响应拦截器中,根据状态码进行一些统一的操作。
    const token = store.state.token;
    token && (config.headers.Authorization = token);
    return config;
  },
  error => Promise.error(error)
);

// 响应拦截器
instance.interceptors.response.use(
  // 请求成功
  res => {
    if(res.status>=200 && res.status<300) {
      let data = res.data;
      if(data.code<=0) {
        tip(data.message);
        return;
      }else {
        return Promise.resolve(data);
      }
    }
    return Promise.reject(res);
  },
  // 请求失败
  error => {
    const { response } = error;
    if (response) {
      // 请求已发出,但是不在2xx的范围
      errorHandle(response.status, response.data.message);
      return Promise.reject(response);
    } else {
      // 处理断网的情况
      // eg:请求超时或断网时,更新state的network状态
      // network状态在app.vue中控制着一个全局的断网提示组件的显示隐藏
      // 关于断网组件中的刷新重新获取数据,会在断网组件中说明
      if (!window.navigator.onLine) {
        store.commit("changeNetwork", false);
      } else {
        return Promise.reject(error);
      }
    }
  }
);

export default instance;
// axios/api/myPurse.js
/** 
 * 
 * 我的钱包接口
*/
import axios from '../http'

const concatData = function(data){
    const defaultData = {
        userGuid: sessionStorage.getItem('guid')
    };
    return typeof data === 'object'&& Object.keys(data).lentgh ? {...defaultData,...data}:defaultData;
}




 const accountBaseUrl = '/balanceAccount';
// 获取账户余额

const balance = function(data) {
    data = concatData(data);
    return axios.post(`${accountBaseUrl}/balance`,data);
}
// 提现申请
 const withdraw = function() {
    return axios.post(`${accountBaseUrl}/withdraw`);
}

// 交易记录
 const transactionRecords = function() {
    return axios.post(`${accountBaseUrl}/transactionRecords`);
}

// 设置(重置)交易密码
const resetTransactionPassword = function() {
    return axios.post(`${accountBaseUrl}/resetTransactionPassword`);
}

// 修改交易密码
 const updateTransactionPassword = function() {
    return axios.post(`${accountBaseUrl}/updateTransactionPassword`);
}

// 托管资金
 const deposit = function() {
    return axios.post(`/tenderee/deposit`);
}

export default {
    balance,
    withdraw,
    transactionRecords,
    resetTransactionPassword,
    updateTransactionPassword,
    deposit
}