{
a: 'http://...',
b: '<html>...</html>'
}
/**
* @description:解析html
*/
export default {
data () {
return {
//解析后的对象
htmlModel:{}
};
},
methods: {
/**
* @description:解析html
* @param data:需要解析的对象
* @param args:指定解析的key
*/
resolver (data, ...args) {
let htmlModel = Object.assign({}, data);
let requestArray = [];
//判断是否是指定解析
if (args.length > 0) {
args.forEach((item, index) => {
if (data[item] && this.isHttp(data[item])) {
requestArray.push(item);
this.requestHtml(data[item], htmlModel, item, args);
} else if (data[item]) {
//写入数据
htmlModel[item] = data[item];
this.call(htmlModel, args);
} else {
this.call(htmlModel, args);
}
});
//按照正常解析
} else {
for (let key in data) {
if (data[key] && this.isHttp(data[key])) {
requestArray.push(key);
this.requestHtml(data[key], htmlModel, key);
} else {
//写入数据
htmlModel[key] = data[key];
this.call(htmlModel);
}
}
}
},
/**
* @description:防止属性值为URL的数据未请求回来
* @param data:需要解析的对象
* @param args:指定解析的key
*/
call (htmlModel, args) {
let callMap = {};
if (args && args.length > 0) {
callMap = Object.assign({}, htmlModel);
for (let i = 0; i < args.length; i++) {
if (this.isHttp(callMap[args[i]])) {
callMap[args[i]] = '';
}
}
this.parseSuccess(callMap);
} else {
for (let key in htmlModel) {
if (!this.isHttp(htmlModel[key])) {
callMap[key] = htmlModel[key];
} else {
callMap[key] = '';
}
}
this.parseSuccess(callMap);
}
},
/**
* @description:执行axios请求
* @param requestUrl:请求的url
* @return Promise
*/
requestHtml (requestUrl, htmlModel, key, args) {
let $this = this;
/* eslint-disable no-undef */
return axios({
method:'GET',
url:requestUrl
}).then(response => {
htmlModel[key] = response.data;
$this.call(htmlModel, args);
}).catch(e => {
$this.call(htmlModel, args);
});
},
/**
* @description:判断是否是http/https请求
* @param str:需要校验的字符串
* @returns Boolean
*/
isHttp (str) {
let regex = /^http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?$/;
return regex.test(str);
}
}
};
解析字段
最新推荐文章于 2024-07-31 10:12:53 发布