vue将接口封装,封装公共的方法并进行调用
vue将接口封装,封装公共的方法并进行调用
·
将接口封装,调用公共的方法
1.调用公共的方法
1.1先将接口在api文件下面定义好
在api下面
export function getDownValue(type) { return request({ url: '/project-mgt/project/v1.0/getDownValue?type=' + type, method: 'get' }) }
在utils/index.js
import { getDownValue } from "@/code/projectSelection/api/projectSelectionApi"
export function dictionaries(that, key, code) {
getDownValue(code).then(res => {
if (res.data) {
that[key] = [{ name: "全部", value: "" }]
that[key] = [...that[key], ...res.data]
console.log("that[key]", that[key]);
}
});
}
1.2 在vue页面使用
import { dictionaries } from "@/utils";
export default {
name: "",
data() {
// isLike:''
return {
pojectScheduleList:[],
},
},
created() {
let that = this;
dictionaries(that, "pojectScheduleList","project_type");//project_type为传参,pojectScheduleList为此页面的数据
},
}
2.调用公共的格式化时间的方法
2.1.定义
在utils/index.js
export function parseTime(time, cFormat) {
if (arguments.length === 0 || !time) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string')) {
if ((/^[0-9]+$/.test(time))) {
// support "1548221490638"
time = parseInt(time)
} else {
time = time.replace(new RegExp(/-/gm), '/')
}
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key]
// Note: getDay() returns 0 on Sunday
if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
return value.toString().padStart(2, '0')
})
return time_str
}
2.2使用
import { parseTime } from "@/utils";
this.fillTime = parseTime(new Date(), "{y}-{m}-{d}");
3.公共的方法
3.1.定义
在utils/index.js
// get接口,将json参数转换成str,用于拼接到url后面
export function getStrParams(object) {
let str = ""
let num = 0
for (const key in object) {
if (num == 0) {
str += "?" + key + "=" + object[key]
} else {
str += "&" + key + "=" + object[key]
}
num = 1
}
return str
}
//定义全局
import { getStrParams} from '@/utils/index';
// import hex_md5 from '@/utils/md5';
Vue.prototype.$getStrParams= getStrParams;
let params={
id:"2134124",
name:"张三",
}
let url=this.$getStrParams(params)
//?id=2134124&name=张三
//解密
//decodeURIComponent()
//let common = JSON.parse(decodeURIComponent(url))
更多推荐


所有评论(0)