vue接口请求加密实例
程序员文章站
2022-05-02 19:50:03
1. 安装vue项目 npm init webpack project2 安装iview npm i iview --save (这里是结合iview框架使用的 可根据自己的需求安装 当然也可以不安装...
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接口请求加密实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
上一篇: 微信公众号置顶精选留言有哪些要求?