电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

vue接口請求加密實例

瀏覽:103日期:2022-12-10 10:00:14

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

// 公共使用的filtersimport Vue from ’vue’;import {getTime, getPrdType} from ’../utils/time’; // 區分支付方式的filterVue.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];});// 分割以:連接多個參數的stringVue.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);});// 處理圖片地址的filterVue.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*60axios.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 httpexport 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())}// 刪除cookieexport 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() }}// 設置localstorageexport function putlocal (key, value) { if (!key || !value) return window.localStorage[key] = JSON.stringify(value)}// 獲取localstorageexport 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 = falseVue.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接口請求加密實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Vue
相關文章:
主站蜘蛛池模板: 大_小鼠elisa试剂盒-植物_人Elisa试剂盒-PCR荧光定量试剂盒-上海一研生物科技有限公司 | 房屋质量检测-厂房抗震鉴定-玻璃幕墙检测-房屋安全鉴定机构 | 防水套管|柔性防水套管|伸缩器|伸缩接头|传力接头-河南伟创管道 防水套管_柔性防水套管_刚性防水套管-巩义市润达管道设备制造有限公司 | 高铝轻质保温砖_刚玉莫来石砖厂家_轻质耐火砖价格 | 基本型顶空进样器-全自动热脱附解吸仪价格-AutoHS全模式-成都科林分析技术有限公司 | 上海律师咨询_上海法律在线咨询免费_找对口律师上策法网-策法网 广东高华家具-公寓床|学生宿舍双层铁床厂家【质保十年】 | 防火板_饰面耐火板价格、厂家_品牌认准格林雅 | 医学模型生产厂家-显微手术模拟训练器-仿真手术模拟训练系统-北京医教科技 | 滑板场地施工_极限运动场地设计_滑板公园建造_盐城天人极限运动场地建设有限公司 | 全自动端子机|刺破式端子压接机|全自动双头沾锡机|全自动插胶壳端子机-东莞市傅氏兄弟机械设备有限公司 | 智能气瓶柜(大型气瓶储存柜)百科 | 沈阳楼承板_彩钢板_压型钢板厂家-辽宁中盛绿建钢品股份有限公司 轴承振动测量仪电箱-轴承测振动仪器-测试仪厂家-杭州居易电气 | 环比机械| 阿尔法-MDR2000无转子硫化仪-STM566 SATRA拉力试验机-青岛阿尔法仪器有限公司 | 上海办公室装修_上海店铺装修公司_厂房装潢设计_办公室装修 | 【电子厂招聘_普工招工网_工厂招聘信息平台】-工立方打工网 | 希望影视-高清影视vip热播电影电视剧免费在线抢先看 | 叉车电池-叉车电瓶-叉车蓄电池-铅酸蓄电池-电动叉车蓄电池生产厂家 | 北京环球北美考试院【官方网站】|北京托福培训班|北京托福培训 | 联系我们老街华纳娱乐公司官网19989979996(客服) | 塑料熔指仪-塑料熔融指数仪-熔体流动速率试验机-广东宏拓仪器科技有限公司 | 山东锐智科电检测仪器有限公司_超声波测厚仪,涂层测厚仪,里氏硬度计,电火花检漏仪,地下管线探测仪 | 纯化水设备-EDI-制药-实验室-二级反渗透-高纯水|超纯水设备 | 喷砂机厂家_自动除锈抛丸机价格-成都泰盛吉自动化喷砂设备 | 电动手术床,医用护理床,led手术无影灯-曲阜明辉医疗设备有限公司 | 游戏版号转让_游戏资质出售_游戏公司转让-【八九买卖网】 | 广州云仓代发-昊哥云仓专业电商仓储托管外包代发货服务 | 翅片管换热器「型号全」_厂家-淄博鑫科环保 | SDI车窗夹力测试仪-KEMKRAFT方向盘测试仪-上海爱泽工业设备有限公司 | 家用净水器代理批发加盟_净水机招商代理_全屋净水器定制品牌_【劳伦斯官网】 | 全温恒温摇床-水浴气浴恒温摇床-光照恒温培养摇床-常州金坛精达仪器制造有限公司 | 英国雷迪地下管线探测仪-雷迪RD8100管线仪-多功能数字听漏仪-北京迪瑞进创科技有限公司 | 深圳市万色印象美业有限公司 | 国资灵活用工平台_全国灵活用工平台前十名-灵活用工结算小帮手 | 天津力值检测-天津管道检测-天津天诚工程检测技术有限公司 | NM-02立式吸污机_ZHCS-02软轴刷_二合一吸刷软轴刷-厦门地坤科技有限公司 | 知企服务-企业综合服务(ZiKeys.com)-品优低价、种类齐全、过程管理透明、速度快捷高效、放心服务,知企专家! | 工程管道/塑料管材/pvc排水管/ppr给水管/pe双壁波纹管等品牌管材批发厂家-河南洁尔康建材 | 胜为光纤光缆_光纤跳线_单模尾纤_光纤收发器_ODF光纤配线架厂家直销_北京睿创胜为科技有限公司 - 北京睿创胜为科技有限公司 | 机械加工_绞车配件_立式离心机_减速机-洛阳三永机械厂 | 健康管理师报名入口,2025年健康管理师考试时间信息网-网站首页 塑料造粒机「厂家直销」-莱州鑫瑞迪机械有限公司 |