vue接口请求加密实例


Posted in Javascript onAugust 11, 2020

1. 安装vue项目 npm init webpack project

2 安装iview npm i iview --save (这里是结合iview框架使用的 可根据自己的需求安装 当然也可以不安装)

3 在src目录下建一个utils文件夹 里面需要放5个js 都是封装好的js文件 功能不仅仅局限于加密 可以研究一下 你会学到很多东西

1.api.js

/**
 * 为vue实例添加http方法
 * Vue.use(http)
 */
import http from './http'
 
export default {
 /**
 * install钩子
 * @param {Vue} Vue Vue
 */
 install (Vue) {
 Vue.prototype.http = http
 }
}

2. filters.js

// 公共使用的filters
import Vue from 'vue';
import {getTime, getPrdType} from '../utils/time';
 
 
// 区分支付方式的filter
Vue.filter('paywayType', function (value) {
 return value;
});
 
// 时间
Vue.filter('newdate', function (value) {
 return getTime(value);
});
// 时间-分钟
Vue.filter('minute', function (str, n) {
 const num = parseInt(n);
 return str.split(' ')[num];
});
// 分割以:连接多个参数的string
Vue.filter('valStr', function (str, n) {
 const num = parseInt(n);
 return str.split(':')[num];
});
// 根据提供时间计算倒计时
Vue.filter('countDown', function (str) {
 const dateStr = new Date(str).getTime();
 const timeNow = new Date().getTime();
 const countDown = dateStr - timeNow;
 const countDownDay = Math.floor((dateStr - timeNow) / 86400000);// 计算剩余天数
 const countDownHour = Math.floor((dateStr - timeNow) / 3600000 % 24);// 计算剩余小时
 const countDownMin = Math.floor((dateStr - timeNow) / 60000 % 60);// 计算剩余分钟
 // const countDownSec = Math.floor((dateStr - timeNow) / 1000 % 60);// 计算剩余秒
 if (countDown <= 0) {
  return '- - - -';
 } else {
  return countDownDay + '天' + countDownHour + '小时' + countDownMin + '分钟';
 }
});
// 取绝对值
Vue.filter('numberFn', function (numberStr) {
 return Math.abs(numberStr);
});
// 处理图片地址的filter
Vue.filter('imgSrc', function (src) {
 const env = getPrdType();
 switch (env) {
  case 'pre':
   return `https://preres.bldz.com/${src}`;
  case 'pro':
   return `https://res.bldz.com/${src}`;
  case 'test':
  default:
   return `https://testimg.bldz.com/${src}`;
 }
});
// 直接转化剩余时间
Vue.filter('dateShow', function (dateStr) {
 const countDownDay = Math.floor(dateStr / 86400);// 计算剩余天数
 const countDownHour = Math.floor(dateStr / 3600 % 24);// 计算剩余小时
 const countDownMin = Math.floor(dateStr / 60 % 60);// 计算剩余分钟
 // const countDownSec = Math.floor((dateStr - timeNow) / 1000 % 60);// 计算剩余秒
 if (dateStr <= 0) {
  return '- - - -';
 } else if (countDownDay <= 0 && countDownHour <= 0) {
  return countDownMin + '分钟';
 } else if (countDownDay <= 0) {
  return countDownHour + '小时' + countDownMin + '分钟';
 } else {
  return countDownDay + '天' + countDownHour + '小时' + countDownMin + '分钟';
 }
});
// 处理图片
Vue.filter('imgLazy', function (src) {
 return {
  src,
  error: '../static/images/load-failure.png',
  loading: '../static/images/default-picture.png'
 };
});
Vue.filter('imgHandler', function (src) {
 return src.replace(/,jpg/g, '.jpg');
});

3.http.js

import axios from 'axios'
import utils from '../utils/utils'
import {Modal} from 'iview'
// import qs from 'qs';
axios.defaults.timeout = 1000*60
axios.defaults.baseURL = ''
const defaultHeaders = {
 Accept: 'application/json, text/plain, */*; charset=utf-8',
 'Content-Type': 'application/json; charset=utf-8',
 Pragma: 'no-cache',
 'Cache-Control': 'no-cache'
}
// 设置默认头
Object.assign(axios.defaults.headers.common, defaultHeaders)
 
const methods = ['get', 'post', 'put', 'delete']
 
const http = {}
methods.forEach(method => {
 http[method] = axios[method].bind(axios)
})
export default http
export const addRequestInterceptor =
 axios.interceptors.request.use.bind(axios.interceptors.request)
// request前自动添加api配置
addRequestInterceptor(
 (config) => {
 if (utils.getlocal('token')) {
  // 判断是否存在token,如果存在的话,则每个http header都加上token
  config.headers.Authentication = utils.getlocal('token')
 }
 // config.url = `/api${config.url}`
 return config
 },
 (error) => {
 return Promise.reject(error)
 }
)
 
export const addResponseInterceptor =
axios.interceptors.response.use.bind(axios.interceptors.response)
addResponseInterceptor(
 (response) => {
 // 在这里统一前置处理请求响应
 if (Number(response.status) === 200) {
  // 全局notify有问题,还是自己处理吧
  // return Promise.reject(response.data)
  // window.location.href = './'
  // this.$router.push({ path: './' })
 }
 return Promise.resolve(response.data)
 },
 (error) => {
 if (error.response) {
  const title = '温馨提示';
  const content = '<p>登录过期请重新登录</p>'  
  switch (error.response.status) {
  case 401:
   // 返回 401 跳转到登录页面  
   Modal.error({
   title: title,
   content: content,
   onOk: () => {
    localStorage.removeItem("lefthidden")
    localStorage.removeItem("leftlist")
    localStorage.removeItem("token")
    localStorage.removeItem("userInfo")
    localStorage.removeItem("headace")
    localStorage.removeItem("sideleft")
    utils.delCookie("user");
    window.location.href = './'
   }
  })
   break
  }
 }
 return Promise.reject(error || '出错了')
 }
)

4. time.js

// 常用的工具api
 
const test = 'test';
const pre = 'pre';
const pro = 'pro';
 
export function judeType (param, typeString) {
 if (Object.prototype.toString.call(param) === typeString) return true;
 return false;
};
 
export function isPrd () {
 return process.env.NODE_ENV === 'production';
};
 
export function getPrdType () {
 return ENV;
};
 
export const ls = {
 put (key, value) {
  if (!key || !value) return;
  window.localStorage[key] = JSON.stringify(value);
 },
 get (key) {
  if (!key) return null;
  const tem = window.localStorage[key];
  if (!tem) return null;
  return JSON.parse(tem);
 },
 // 设置cookie
 setCookie (key, value, time) {
  if (time) {
   let date = new Date();
   date.setDate(date.getDate() + time);
   document.cookie = key + '=' + value + ';expires=' + date.toGMTString() + ';path=/';
  } else {
   document.cookie = key + '=' + value + ';path=/';
  }
 },
 // 获取cookie
 getCookie (key) {
  let array = document.cookie.split('; ');
  array.map(val => {
   let [valKey, value] = val.split('=');
   if (valKey === key) {
    return decodeURI(value);
   }
  });
  return '';
 }
};
 
/**
 * 判断元素有没有该class
 * @param {*} el
 * @param {*} className
 */
 
export function hasClass (el, className) {
 let reg = new RegExp('(^|\\s)' + className + '(\\s|$)');
 return reg.test(el.className);
}
/**
 * 为元素添加class
 * @param {*} el
 * @param {*} className
 */
export function addClass (el, className) {
 if (hasClass(el, className)) return;
 let newClass = el.className.spilt(' ');
 newClass.push(className);
 el.className = newClass.join(' ');
}
 
export function removeClass (el, className) {
 if (!hasClass(el, className)) return;
 
 let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g');
 el.className = el.className.replace(reg, ' ');
}
 
/**
 * 将数据存储在标签里
 * @param {*} el
 * @param {*} name
 * @param {*} val
 */
export function getData (el, name, val) {
 let prefix = 'data-';
 if (val) {
  return el.setAttribute(prefix + name, val);
 }
 return el.getAttribute(prefix + name);
}
 
export function isIphone () {
 return window.navigator.appVersion.match(/iphone/gi);
}
 
/**
 * 计算元素和视窗的位置关系
 * @param {*} el
 */
export function getRect (el) {
 if (el instanceof window.SVGElement) {
  let rect = el.getBoundingClientRect();
  return {
   top: rect.top,
   left: rect.left,
   width: rect.width,
   height: rect.height
  };
 } else {
  return {
   top: el.offsetTop,
   left: el.offsetLeft,
   width: el.offsetWidth,
   height: el.offsetHeight
  };
 }
}
 
/**
 * 获取不确定数据的方法api
 * @param {Array} p 参数数组
 * @param {Object} o 对象
 */
export function getIn (p, o) {
 return p.reduce(function (xs, x) {
  return (xs && xs[x]) ? xs[x] : null;
 }, o);
}
 
/**
 * 时间戳改为年月日格式时间
 * @param {*} p 时间戳
 */
export function getTime (p) {
 let myDate = new Date(p);
 let year = myDate.getFullYear();
 let month = myDate.getMonth() + 1;
 let date = myDate.getDate();
 if (month >= 10) {
  month = '' + month;
 } else {
  month = '0' + month;
 }
 
 if (date >= 10) {
  date = '' + date;
 } else {
  date = '0' + date;
 }
 return year + '-' + month + '-' + date;
}
 
export function debounce (method, delay) {
 let timer = null;
 return function () {
  let context = this;
  let args = arguments;
  clearTimeout(timer);
  timer = setTimeout(function () {
   method.apply(context, args);
  }, delay);
 };
}

5 utils.js

// 获取cookie、
export function getCookie (name) {
 if (document.cookie.length > 0){
 let c_start = document.cookie.indexOf(name + '=')
 if (c_start != -1) { 
  c_start = c_start + name.length + 1 
  let c_end = document.cookie.indexOf(';', c_start)
  if (c_end == -1) c_end = document.cookie.length
  return unescape(document.cookie.substring(c_start, c_end))
 }
 }
 return ''
}
// 设置cookie,增加到vue实例方便全局调用
export function setCookie (cname, value, expiredays) {
 let exdate = new Date()
 exdate.setDate(exdate.getDate() + expiredays)
 document.cookie = cname + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString())
}
// 删除cookie
export function delCookie (name) {
 let exp = new Date()
 exp.setTime(exp.getTime() - 1)
 let cval = getCookie(name)
 if (cval != null) {
 document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString()
 }
}
// 设置localstorage
export function putlocal (key, value) {
 if (!key || !value) return
 window.localStorage[key] = JSON.stringify(value)
}
// 获取localstorage
export function getlocal (key) {
 if (!key) return null
 const tem = window.localStorage[key]
 if (!tem) return null
 return JSON.parse(tem)
}
/**
 * use_iframe_download function - 通过 iframe 下载文件
 *
 * @param {String} download_path 需下载文件的链接
 * @return {Void}
 */
export const use_iframe_download = download_path => {
 const $iframe = document.createElement('iframe')
 
 $iframe.style.height = '0px'
 $iframe.style.width = '0px'
 document.body.appendChild($iframe)
 $iframe.setAttribute('src', download_path)
 
 setTimeout(function () { $iframe.remove() }, 20000)
}
 
function requestTimeout (xhr) {
 const timer = setTimeout(() => {
 timer && clearTimeout(timer)
 xhr.abort()
 }, 5000)
 return timer
}
// 导出
export function exporttable (httpUrl,token, formData, callback) {
let i = formData.entries();
 let param = "?Authentication="+token;
 do{
 var v = i.next();
 if(!v.done){
  param+="&"+v.value[0]+"="+v.value[1];  
 }
 
 }while(!v.done);
// console.log(param);
window.open(httpUrl+param)
// var xhr = new XMLHttpRequest()
// if (xhr.withCredentials === undefined){ 
// return false
// };
// xhr.open("post", httpUrl)
// // xhr.timeout=5000
// xhr.setRequestHeader("Authentication", token)
// xhr.responseType = "blob"
// let timer = requestTimeout(xhr)
// xhr.onreadystatechange = function () {
// timer && clearTimeout(timer)
// if (xhr.readyState !== 4) {
// timer = requestTimeout(xhr)
// return
// }
// if (this.status === 200) {
// var blob = this.response
// var contentType = this.getResponseHeader('content-type')
// var fileName = contentType.split(";")[1].split("=")[1]
// fileName = decodeURI(fileName)
// let aTag = document.createElement('a')
// // 下载的文件名
// aTag.download = fileName
// aTag.href = URL.createObjectURL(blob)
// aTag.click()
// URL.revokeObjectURL(blob)
callback && callback(true)
// } else {
// callback && callback(false)
// } 
// }
// xhr.send(formData);
}
 
// 获取当前时间
export function getNowFormatDate() {
 var date = new Date();
 var seperator1 = "-";
 var seperator2 = ":";
 var month = date.getMonth() + 1;
 var strDate = date.getDate();
 if (month >= 1 && month <= 9) {
  month = "0" + month;
 }
 if (strDate >= 0 && strDate <= 9) {
  strDate = "0" + strDate;
 }
 var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
   + " " + date.getHours() + seperator2 + date.getMinutes()
   + seperator2 + date.getSeconds();
   
 return currentdate;
}
 
// 时间格式化
export function formatDate(date, fmt) {
 if (/(y+)/.test(fmt)) {
  fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
 }
 let o = {
  'M+': date.getMonth() + 1,
  'd+': date.getDate(),
  'h+': date.getHours(),
  'm+': date.getMinutes(),
  's+': date.getSeconds()
 };
 for (let k in o) {
  if (new RegExp(`(${k})`).test(fmt)) {
   let str = o[k] + '';
   fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
  }
 }
 return fmt;
};
 
function padLeftZero(str) {
 return ('00' + str).substr(str.length);
}
export default {
 getCookie,
 setCookie,
 delCookie,
 putlocal,
 getlocal,
 exporttable,
 getNowFormatDate,
 formatDate
}

4.配置main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import VueRouter from 'vue-router';
import iView from 'iview';
import 'iview/dist/styles/iview.css'
import http from './utils/http'
import Api from './utils/api'
import utils from './utils/utils'
import './utils/filters'
 
Vue.config.productionTip = false
Vue.use(VueRouter);
Vue.use(iView);
 
Vue.use(http)
Vue.use(Api)
Vue.use(utils)
/* eslint-disable no-new */
 
global.BASE_URL = process.env.API_HOST
 
new Vue({
 el: '#app',
 router,
 components: { App },
 template: '<App/>'
})

5.找到config文件夹下的dev.env.js

module.exports = merge(prodEnv, {
 NODE_ENV: '"development"',
 API_HOST: '"开发环境接口地址"'
})

6.页面中具体使用方法

<template>
 <div class="hello">
  <Select v-model="model8" clearable style="width:200px">
  <Option v-for="item in cityList" :value="item.productCode" :key="item.productCode">{{item.productName }}</Option>
 </Select>
 </div>
</template>
 
<script>
export default {
 name: 'HelloWorld',
 data () {
 return {
  cityList:[],
  model8:"code"
 }
 },
 mounted(){
 this.http
  .post(BASE_URL + "请求路径",{})
  .then(data => {
  if (data.code == "success") {
 this.cityList = data.data;
 this.cityList.splice(0,0,{ productCode: "code", productName: "所有产品" })
  }
  })
  .catch(err => {
  console.log(err);
  });
 }
}
</script>
<style scoped>
</style>

以上这篇vue接口请求加密实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
JavaScript实现统计文本框Textarea字数增强用户体验
Dec 21 Javascript
jQuery中:reset选择器用法实例
Jan 04 Javascript
直接拿来用的15个jQuery代码片段
Sep 23 Javascript
JavaScript测试工具之Karma-Jasmine的安装和使用详解
Dec 03 Javascript
强大的 Angular 表单验证功能详细介绍
May 23 Javascript
w3c编程挑战_初级脚本算法实战篇
Jun 23 Javascript
JS实现按钮颜色切换效果
Sep 05 Javascript
基于node搭建服务器,写接口,调接口,跨域的实例
May 13 Javascript
layer设置maxWidth及maxHeight解决方案
Jul 26 Javascript
vue.js实现二级菜单效果
Oct 19 Javascript
vuex实现像调用模板方法一样调用Mutations方法
Nov 06 Javascript
javascript利用键盘控制小方块的移动
Apr 20 Javascript
vue组件暴露和.js文件暴露接口操作
Aug 11 #Javascript
vue npm install 安装某个指定的版本操作
Aug 11 #Javascript
小程序自动化测试的示例代码
Aug 11 #Javascript
vue自定义组件(通过Vue.use()来使用)即install的用法说明
Aug 11 #Javascript
Vue 实现创建全局组件,并且使用Vue.use() 载入方式
Aug 11 #Javascript
Vue自定义全局弹窗组件操作
Aug 11 #Javascript
基于Vue全局组件与局部组件的区别说明
Aug 11 #Javascript
You might like
成本8450万,票房仅2亿,口碑两极分化,又一部DC电影扑街了
2020/04/09 欧美动漫
PHP基于GD库的缩略图生成代码(支持jpg,gif,png格式)
2014/06/19 PHP
PHP实现递归无限级分类
2015/10/22 PHP
php求今天、昨天、明天时间戳的简单实现方法
2016/07/28 PHP
Laravel基础_关于view共享数据的示例讲解
2019/10/14 PHP
循环 vs 递归浅谈
2013/02/28 Javascript
鼠标放在图片上显示大图的JS代码
2013/03/26 Javascript
jQuery$命名冲突怎么办如何解决
2014/01/16 Javascript
JS 使用for循环遍历子节点查找元素
2014/09/06 Javascript
JS 新增Cookie 取cookie值 删除cookie 举例详解
2014/10/10 Javascript
js使用split函数按照多个字符对字符串进行分割的方法
2015/03/20 Javascript
Javascript实现的SHA-256加密算法完整实例
2016/02/02 Javascript
Spring MVC中Ajax实现二级联动的简单实例
2016/07/06 Javascript
浅谈js停止事件冒泡 阻止浏览器的默认行为(阻止超连接 #)
2017/02/08 Javascript
JS实现搜索关键词的智能提示功能
2017/07/07 Javascript
js实现rem自动匹配计算font-size的示例
2017/11/18 Javascript
关于node-bindings无法在Electron中使用的解决办法
2018/12/18 Javascript
js实现无限瀑布流实例方法
2019/09/16 Javascript
关于引入vue.js 文件的知识点总结
2020/01/28 Javascript
微信公众号网页分享功能开发的示例代码
2020/05/27 Javascript
解决vue-router路由拦截造成死循环问题
2020/08/05 Javascript
[40:19]完美世界DOTA2联赛PWL S3 Rebirth vs CPG 第二场 12.18
2020/12/19 DOTA
Python采集腾讯新闻实例
2014/07/10 Python
Python中操作文件之write()方法的使用教程
2015/05/25 Python
使用Python多线程爬虫爬取电影天堂资源
2016/09/23 Python
numpy创建单位矩阵和对角矩阵的实例
2019/11/29 Python
CSS3的Flexbox布局的简明入门指南
2016/04/08 HTML / CSS
美国半成品食材配送服务商:Home Chef
2018/01/25 全球购物
英国领先的在线鱼贩:The Fish Society
2020/08/12 全球购物
给排水专业应届生求职信
2013/10/12 职场文书
优秀食品类广告词
2014/03/19 职场文书
大学生个人求职信
2014/06/02 职场文书
2014年社区个人工作总结
2014/12/02 职场文书
MySQL数据库压缩版本安装与配置详细教程
2021/05/21 MySQL
详解MySQL中的pid与socket
2021/06/15 MySQL
Win11控制面板快捷键是什么?Win11打开控制面板的方法汇总
2022/07/07 数码科技