一、Vue 全局挂载自定义函数
使用vue 时,有时需要设置公共的函数,便于在所有组件中调用或者在组件的生命周期中都可调用,这便需要自定义全局函数。以下介绍一些全局函数的定义方式。
1、方法一:Vue.prototype
在mian.js中写入函数
Vue.prototype.getToken = function (){
...
}
在所有组件里可调用函数
this.getToken();
2、方法二:exports.install+Vue.prototype
写好自己需要的公共JS文件(fun.js)
exports.install = function (Vue, options) {
Vue.prototype.getToken = function (){
...
};
};
main.js 引入并使用
import fun from './fun' // 路径示公共JS位置决定
Vue.use(fun);
所有组件里可调用函数
this.getToken();
二、 Vue 导出 pdf 清晰版
第一步、安装插件
// 第一个.将页面html转换成图片
npm install --save html2canvas
// 第二个.将图片生成pdf
npm install jspdf --save
第二步、定义全局函数,创建一个htmlToPdf.js文件在指定位置.例如放在(‘src/utils/htmlToPdf’)
// 下面两个package要单独安装
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
install (Vue, options) {
Vue.prototype.getPdf = function () {
var title = this.htmlTitle // DPF标题
html2Canvas(document.querySelector('#pdfCentent'), {
allowTaint: true,
useCORS: true, // 看情况选用上面还是下面的,
dpi: window.devicePixelRatio * 20, // 将分辨率提高到特定的DPI 提高四倍
scale: 10 // 按比例增加分辨率
}).then(function (canvas) {
const contentWidth = canvas.width
const contentHeight = canvas.height
// 一页pdf显示html页面生成的canvas高度;
const pageHeight = (contentWidth / 592.28) * 841.89 // 592.28
// 生成pdf的html页面高度
let leftHeight = contentHeight
// 页面偏移
let position = 0
// a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
const imgWidth = 595.28
const imgHeight = (592.28 / contentWidth) * contentHeight
const pageData = canvas.toDataURL('image/jpeg', 1.0)
const PDF = new JsPDF('', 'pt', 'a4')
// 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
// 当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
})
}
}
}
第三步、在main.js中引入,全局引用
import htmlToPdf from "../src/utils/htmlToPdf"
Vue.use(htmlToPdf)
第四步、在用到的组件 .vue中使用
用此钩子打印导出带名字的pdf
三、 JS 时分秒时间戳 和 hh:mm:ss格式 相互转化
hh:mm:ss -> 时分秒时间戳
timeSec(time) {
if (time !== null) {
var s = "";
var hour = time.split(":")[0];
var min = time.split(":")[1];
var sec = time.split(":")[2];
s = Number(hour * 3600) + Number(min * 60) + Number(sec);
return s;
}
}
时分秒时间戳 -> hh:mm:ss
timeFormat(data) {
var time = Number(data);
var h = Math.floor(time / 3600);
var m = Math.floor((time % 3600) / 60);
var s = parseInt(time % 3600) % 60;
var hh = h < 10 ? "0" + h : h;
var mm = m < 10 ? "0" + m : m;
var ss = s < 10 ? "0" + s : s;
return hh + ":" + mm + ":" + ss;
},