UNPKG

2.03 kBJavaScriptView Raw
1/**
2 * Created by liuzhengdong on 2018/4/3.
3 * 日志打印器 class
4 */
5import { IS_DEBUG } from './../utils/env'
6
7class Logger {
8 /**
9 * 构造函数
10 * @param filename 调用的文件名
11 */
12 constructor(filename) {
13 this.filename = filename
14 }
15}
16
17/**
18 * 定义方法
19 * @type {{info: string, log: string, warn: string, error: string}}
20 */
21const methods = {
22 log: 'color: green',
23 info: 'color:#6495ED',
24 warn: 'color: #cc33cc',
25 error: 'color: red',
26}
27/**
28 * 将方法绑定到原型上
29 */
30Object.entries(methods).forEach(([method, color]) => {
31 Logger.prototype[method] = function (...args) {
32 // 非生产环境
33 if (!IS_DEBUG) {
34 return
35 }
36 args.unshift(`%c[${this.filename}]:`, color)
37 console[method](...args)
38 }
39})
40
41/**
42 * 定义 VueLogger class
43 */
44class VueLogger {
45 constructor(filename) {
46 const logger = new Logger(filename)
47 Object.keys(methods).forEach(method => {
48 this[method] = (vm, ...args) => {
49 // 不存在vue实例时,简单打印
50 if (!vm) {
51 return
52 }
53 if (vm._isVue !== true) {
54 logger[method].call(logger, vm, ...args)
55 return
56 }
57 // 组件当前__file
58 const filePath = vm.$options._parentVnode.componentOptions.Ctor.options.__file
59 // 截取组件名称
60 const componentName = filePath.slice(filePath.lastIndexOf('/') + 1) || '(unkonwn component name)'
61 // 当前路由路径
62 const fullPath = vm.$f7Route ? vm.$f7Route.url : '/'
63 logger[method].call(logger, ...args, `@${componentName}`, `#${fullPath}`)
64 }
65 })
66 }
67}
68
69const vueLogger = new VueLogger('component')
70const componentLogger = {}
71/**
72 * 暴露install钩子,供vue注册
73 * @param {Vue} Vue - Vue构造器类
74 */
75componentLogger.install = function (Vue) { // 基础打印器
76 Object.keys(methods).forEach((method) => {
77 Vue.prototype[method] = function (...args) {
78 vueLogger[method].call({}, this, ...args)
79 }
80 })
81}
82
83export default componentLogger
\No newline at end of file