Vue打印错误日志问题

Vue3全局方法和静态配置文件的最佳实践

Vue3中打印错误日志的最佳实践: 推荐引入全局自定义方法clog,任何地方打印任何类型

在Vue3.0中全局的方法一般有下面两个

  • 方式一 使用 app.config.globalProperties
  • 方式二 通过依赖和注入(provide 和 inject)来完成

但是这两种方法使用起来都非常的不方便

推荐如下方案

Vue3全局方法最佳方案

1,添加一个工具类,例如utils.ts

import moment from "moment";
// 判断对象,数组,字符串是否为空,例如:  undefined , null , '' , '   ' , {}  , [] 全部判断为空
export function isNull(obj: any): boolean {
        if (obj === null || obj === undefined) {
                return true
        }
        if (typeof obj === 'object') {
                let json = JSON.stringify(obj)
                if (json === '{}') {
                        return true
                }
                if (json === '[]') {
                        return true
                }
                return false
        }
        let str = String(obj)
        if (str === 'undefined' || str === 'null' || str === '' || !str || !/[^\s]/.test(str)) {
                return true
        }
        return false
}
// 控制台日志,支持传一个参数(对象/字符串), 也支持传两个参数(标志,日志消息<可以是对象,可以是字符串>)
export function clog(flag, value: any = 'xxxxxxxxxxxxxxxxxxx=Default-value_override+xxxxxxxxxxxxxxxxx'): string {
        try {
                let tmp = ""
                // 如果value为默认值,则没有传递第二个参数,只处理第一个参数
                if (value === `xxxxxxxxxxxxxxxxxxx=Default-value_override+xxxxxxxxxxxxxxxxx`) {
                        tmp = JSON.stringify(flag);
                        console.log(tmp)
                } else if (isNull(value)) {
                        tmp = JSON.stringify(flag);
                        console.log(tmp + ":")
                } else if (isNull(flag)) {
                        tmp = JSON.stringify(value);
                        console.log(":" + tmp)
                } else {
                        tmp = JSON.stringify(value);
                        console.log(flag + ":" + tmp)
                }
                return tmp
        } catch (err) {
                console.log("log", err)
                return " 空对象或者空字符串 "
        }
}
// 日期格式化
export function dateFormatter(str, isDate = false) {
        if (isNull(str)) return undefined
        if (isDate === true) {
                return moment(str).format(
                        'YYYY-MM-DD'
                )
        } else {
                return moment(str).format(
                        'YYYY-MM-DD HH:mm:ss'
                )
        }
}
//把日期字符串转换为纯数字,例如20191231235959
export function dateFormatterNumber(str, hasTime = true, hasSecond = true): string {
        let d = new Date(str);
        if (isNull(str)) {
                let d = new Date();
        }
        let year = d.getFullYear();
        let month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
        let day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
        if (hasTime) {
                let hour = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
                let minute = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
                let second = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
                console.log(year, month, day, year + "" + month + "" + day + "" + hour + "" + minute + "" + (hasSecond === true ? second : ""))
                return year + "" + month + "" + day + "" + hour + "" + minute + "" + (hasSecond === true ? second : "");
        } else {
                return year + "" + month + "" + day;
        }
}
//表单校验
export async function validate(ref: any) {
  if (ref == null) {
    return true
  }
  let isValidate = true
  await ref.validate((valid, fields) => {
    if (valid) {
    } else {
      isValidate = false
      console.log('validate false!', fields)
    }
  })
  return isValidate
}
// 节流
export function throttle(this: any, fn: Function, interval = 500) {
        let last = 0;
        return (...args) => {
                let now = +new Date();
                // 还没到时间
                if (now - last < interval) return;
                last = now;
                fn.apply(this, args);
        };
}
export function html2Escape(sHtml: string) {
        const dict = { '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' };
        return sHtml.replace(/[<>&"]/g, (c: string) => {
                return dict[c];
        });
}
//防抖动
let timestamp, timeout
export function debounce(func, wait, immediate) {
        let args, context, result
        const later = () => {
                // 距离上一次触发的时间间隔
                const last = (timestamp === undefined ? 0 : +new Date() - timestamp)
                // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
                if (last < wait && last > 0) {
                        //是否等待时间间隔达到后调用防抖 加上条件判断防止时间间隔内连续触发多个定时任务
                        if (timeout == null) timeout = setTimeout(later, wait - last)
                } else {
                        timeout = null
                        // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
                        if (!immediate) {
                                timestamp = +new Date()
                                result = func.apply(context, args)
                                if (!timeout) context = args = null
                        }
                }
        }
        return later()
}
/**
 * 对象数组深拷贝
 * @param {Array,Object} source 需要深拷贝的对象数组
 * @param {Array} noClone 不需要深拷贝的属性集合
 */
export function deepClone(source: any, noClone: string[] = []): any {
        if (!source && typeof source !== 'object') {
                throw new Error('error arguments deepClone')
        }
        const targetObj: any = source.constructor === Array ? [] : {}
        Object.keys(source).forEach((keys: string) => {
                if (source[keys] && typeof source[keys] === 'object' && noClone.indexOf(keys) === -1) {
                        targetObj[keys] = deepClone(source[keys], noClone)
                } else {
                        targetObj[keys] = source[keys]
                }
        })
        return targetObj
}

2,这么用

import { clog, isNull } from '@/utils'
clog(jsonObj)

Vue3引入静态配置文件最佳方案

1,在public目录下面添加一个配置文件config.js

2,在html.index文件中引入此文件

3,在vue文件中直接访问就行

config.js

const config = {
  BaseApiUrl: 'http://localhost:44311/',
  Version: '2.0.20220506',
}

html.index

<!DOCTYPE html>
<html >
  <head>
    <title>Vue3Vite</title>
    <script type="text/javascript" src="tools.js"></script>
    <script type="text/javascript" src="config.js"></script>
  </head>
  <body>
    <div ></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

使用举例

import axios from 'axios'
// 创建axios对象,设置baseURL
const service = axios.create({
  baseURL: config.BaseApiUrl + '/', // 直接访问config对象即可
  timeout: 30000,
})
export default service

Vue3全局方法方案二

1.先吧全局方法写到tools.js文件中

tools.js

//动态创建vue对象
const mountPrintData = function (printData, vhtmlDivId = 'print') {
  clog('mountPrintData')
  clog(printData)
  const App = {
    data() {
      return {
        data: printData,
      }
    },
  }
  const app = Vue.createApp(App)
  app.mount('#' + vhtmlDivId)
}
// 控制台日志,支持传一个参数(对象/字符串), 也支持传两个参数(标志,日志消息<可以是对象,可以是字符串>)
const clog = function (flag, value = 'xxxxxxxxxxxxxxxxxxx=Default-value_override+xxxxxxxxxxxxxxxxx') {
  try {
    let tmp = ''
    // 如果value为默认值,则没有传递第二个参数,只处理第一个参数
    if (value === `xxxxxxxxxxxxxxxxxxx=Default-value_override+xxxxxxxxxxxxxxxxx`) {
      tmp = JSON.stringify(flag)
      console.log(tmp)
    } else if (isNull(value)) {
      tmp = JSON.stringify(flag)
      console.log(tmp + ':')
    } else if (isNull(flag)) {
      tmp = JSON.stringify(value)
      console.log(':' + tmp)
    } else {
      tmp = JSON.stringify(value)
      console.log(flag + ':' + tmp)
    }
    return tmp
  } catch (err) {
    console.log('log', err)
    return ' 空对象或者空字符串 '
  }
}
// 判断对象,数组,字符串是否为空,例如:  'undefined' , 'null' , '' , '   ' , {}  , [] 全部判断为空
const isNull = function (obj) {
  if (typeof obj === 'object') {
    let json = JSON.stringify(obj)
    if (json === '{}') {
      return true
    }
    if (json === '[]') {
      return true
    }
    return false
  }
  let str = String(obj)
  if (str === 'undefined' || str === 'null' || str === '' || !str || !/[^\s]/.test(str)) {
    return true
  }
  return false
}

2.在Index.html中引入

按如下引入后tools.js中的方法就可以在任何位置直接使用了

<script type="text/javascript" src="tools.js"></script>

3.在ts,js代码中直接使用

<template>
 ...
</template>
<script >
export default {
  setup() {
    clog(`test`)  //直接使用
  }
}
</script>

Vue2中打印日志的最佳实践

在vue的单页面应用中建议在public目录添加如下的tools.js全局js静态方法

在index.html中这样引用:

<script type="text/javascript" src="tools.js"></script>

如此,在任何地方打印控制台日志就可以这么写: clog(xxx) xxx可以是字符串,也可以是对象。

PS: 打印json对象简单的方法: console.log(JSON.stringify(jsonObj))

tools.js

//判断对象,数组,字符串等是否为空
function isNull(obj){
        let str = String(obj)
        if (str === 'undefined' || str === 'null' || str === '' || !str || !/[^\s]/.test(str)) {
                return true
        }
        if (typeof obj === 'object') {
                let json = JSON.stringify(obj)
                if (json === '{}') {
                        return true
                }
                if (json === '[]') {
                        return true
                }
                return false
        } else {
                return false
        }
}
// 控制台日志,支持传一个参数(对象/字符串), 也支持传两个参数(标志,日志消息<可以是对象,可以是字符串>)
function clog(flag, value= 'xxxxxxxxxxxxxxxxxxx=Default-value_override+xxxxxxxxxxxxxxxxx') {
        try {
                // 如果value为默认值,则没有传递第二个参数,只处理第一个参数
                if (value === `xxxxxxxxxxxxxxxxxxx=Default-value_override+xxxxxxxxxxxxxxxxx`) {
                        let tmp = JSON.stringify(flag);
                        console.log(tmp)
                } else if (isNull(value)) {
                        let tmp = JSON.stringify(flag);
                        console.log(tmp + ":")
                } else if (isNull(flag)) {
                        let tmp = JSON.stringify(value);
                        console.log(":" + tmp)
                } else {
                        let tmp = JSON.stringify(value);
                        console.log(flag + ":" + tmp)
                }
        } catch (err) {
                console.log("log", err)
        }
}
//深拷贝对象
function copySelf(obj) {
  var newobj = obj.constructor === Array ? [] : {};
  if (typeof obj !== "object") {
    return;
  }
  for (var i in obj) {
    newobj[i] = typeof obj[i] === "object" ? copySelf(obj[i]) : obj[i];
  }
  return newobj;
}
//批量导入局部组件 (批量导入全局组件参见vue官网)
//使用方法 components: importComponents(require.context('./', false, /Yi.*\.vue$/)),  // 导入当前目录以"Yi" 开头,以".vue"结尾的全部组件
//require.context('./components', false, /Yi.*\.vue$/) : webpack的方法, 第一个参数为文件路径, 第二个参数为是否包含子文件夹, 第三个参数为正则
function importComponents(comps) {
  let res_components = {}
  comps.keys().forEach((fileName) => {
    let comp = comps(fileName)
    res_components[fileName.replace(/^\.\/(.*)\.\w+$/, '$1')] = comp.default
  })
  return res_components
}
//获取当前时间, 出参为格式化后的日期字符串
function timeNow() {
  var time = new Date();  // 程序计时的月从0开始取值后+1  
  var m = time.getMonth() + 1;
  var t = time.getFullYear() + "-" + m + "-" + time.getDate() + " " + time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
  return t;
}
//一天的开始, 入参为Date类型, 出参为格式化后的日期字符串
function timeDayBegin(time) {
  var m = time.getMonth() + 1;
  var t = time.getFullYear() + "-" + m + "-" + time.getDate() + " 00:00:00";
  return t;
}
//一天的结束, 入参为Date类型, 出参为格式化后的日期字符串
function timeDayEnd(time) {
  var m = time.getMonth() + 1;
  var t = time.getFullYear() + "-" + m + "-" + time.getDate() + " 23:59:59";
  return t;
}
//字符串数组转整型数字键
function strArr2IntArr(arrStr) {
  for (var i = 0; i < arrStr.length; i++) {
    arrStr[i] = parseFloat(arrStr[i])
  }
  return arrStr;
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/zheyiw/article/details/89512590