console简介
console 是一个用于调试和记录信息的内置对象, 提供了多种方法,可以帮助开发者输出各种信息,进行调试和分析。
console.log() 、console.info() :
输出信息,两者类似,但在某些浏览器中可能有不同的样式
console.warn() :
输出警告信息,通常会以黄色背景或带有警告图标的样式显示
console.error() :
输出错误信息,通常会以红色背景或带有错误图标的样式显示
痛点
上述可见打印出来的信息比较复杂,遇到大量复杂的数据打印观感弱
、辨识度低
技术方案
console.log() 可以接受任何类型的参数,包括字符串
、数字
、布尔值
、对象
、数组
、函数
等。最厉害的是,它支持占位符!
常用的占位符:
- %s - 字符串
- %d or %i - 整数
- %f - 浮点数
- %o - 对象
- %c - CSS 样式
格式化字符串
console.log() 支持类似于 C 语言 printf 函数的格式化字符串。我们可以使用占位符来插入变量值。
const name = 'Alice';
const age = 30;
console.log('Name: %s, Age: %d', name, age); // Name: Alice, Age: 30
添加样式
可以使用 %c
占位符添加 CSS 样式,使输出内容更加美观。
console.log('%c This is a styled message', 'color: red; font-size: 20px;');
自定义样式的实现,其实主要是靠%c 占位符添加 CSS 样式实现的!
代码实现
// 实现方法
const createUseLog = () => {
// 为空判断
const isEmpty = (value) => {
return value == null || value === undefined || value === "";
};
// 兼容提示
const compatible = (title="", text="", color="#8b8b8b") => {
let typef = Object.prototype.toString.call(text);
if(typef === "[object String]") {
console.log(
`%c ${title} %c ${text} %c`,
`background:${color};border:1px solid ${color}; padding: 1px; border-radius: 2px 0 0 2px; color: #fff;`,
`border:1px solid ${color}; padding: 1px; border-radius: 0 2px 2px 0; color: ${color};`,
"background:transparent"
);
} else {
console.log(
`%c ${title} %o`,
`background:${color};border:1px solid ${color}; padding: 1px; border-radius: 2px 0 0 2px; color: #fff;`,
text
);
}
};
// 提醒提示
const info = (label="", content="") => {
const title = isEmpty(content) ? "Info" : label;
const text = isEmpty(content) ? label : content;
compatible(title, text, "#8b8b8b");
};
// 错误提示
const error = (label="", content = "") => {
const title = isEmpty(content) ? "Error" : label;
const text = isEmpty(content) ? label : content;
compatible(title, text, "#c70000");
};
// 警告提示
const warning = (label="", content = "") => {
const title = isEmpty(content) ? "Warning" : label;
const text = isEmpty(content) ? label : content;
compatible(title, text, "#ffcd3a");
};
// 成功提示
const success = (label="", content = "") => {
const title = isEmpty(content) ? "Success " : label;
const text = isEmpty(content) ? label : content;
compatible(title, text, "#107010");
};
// 返回
return {
compatible,
info,
error,
warning,
success,
};
};
// 创建打印对象
const log = createUseLog();
使用方法
- 下载依赖
npm i fgconsole
- 引用依赖
import fgconsole from 'fgconsole'
Vue.prototype.$fgconsole = fgconsole;
- 使用
this.$fgconsole.info("提示", "created");