Javascript 如何将console.log绑定到";l";在vue.js中?

Javascript 如何将console.log绑定到";l";在vue.js中?,javascript,vue.js,Javascript,Vue.js,main.js有以下代码 window.l = function () { } try { window.l = console.log.bind(console) } catch (e) { } 在非Vue应用程序中有效。但是打电话的时候, l("test") 在Vue操作/方法中,它抱怨未定义 这怎么行 推理:需要输出一些调试数据,尽可能少地键入。像这样分配console.log window.l=console.log; 当您想向Vue添加全局级功能时,通常应使用混合插件或插件

main.js有以下代码

window.l = function () { }
try {
  window.l = console.log.bind(console)
} catch (e) { }
在非Vue应用程序中有效。但是打电话的时候,

l("test")
在Vue操作/方法中,它抱怨未定义

这怎么行


推理:需要输出一些调试数据,尽可能少地键入。

像这样分配console.log

window.l=console.log;

当您想向Vue添加全局级功能时,通常应使用混合插件插件

对于下一个示例,我假设您正在使用完整的网页模板vue cli。此外,我们将使用
App.vue
作为实际参考,但您可以将相同的原则应用于其他组件


混血儿 使用以下代码创建名为
log.js
(在
mixins
文件夹中)的mixin:

export default {
  methods: {
    l (...args) { // rest parameters
      console.log(...args) // spread operator
    }
  }
}
export default {
  install (Vue, options) {
    Vue.prototype.$l = console.log.bind(console)
    Vue.l = console.log.bind(console)
  }
}
打开
App.vue
,导入mixin并使用它:

<script>
  import log from './mixins/log'

  export default {
    name: 'app',
    mixins: [log],
    created () {
      this.l('Foo', 'Bar') // Foo Bar
    }
  }
</script>
打开您的
main.js
并声明您的全局插件:

import log from './plugins/log'
Vue.use(log)
打开
App.vue
,导入
vue
并使用您的插件:

<script>
  import Vue from 'vue'

  export default {
    name: 'app',
    created () {
      this.$l('Foo') // Foo
      Vue.l('Bar') // Bar
    }
  }
</script>
然后,为了避免ESLint错误,还应该编辑
.eslintrc.js
文件以引用新的全局变量:

globals: {
  l: true
}
该文件如下所示:

// http://eslint.org/docs/user-guide/configuring

module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
    sourceType: 'module'
  },
  globals: {
    l: true
  },
  env: {
    browser: true,
  },
  // https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
  extends: 'standard',
  // required to lint *.vue files
  plugins: [
    'html'
  ],
  // add your custom rules here
  'rules': {
    // allow paren-less arrow functions
    'arrow-parens': 0,
    // allow async-await
    'generator-star-spacing': 0,
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
  }
}
重新启动开发服务器。现在您应该能够在代码中使用
l

<script>
  export default {
    name: 'app',
    created () {
      l('It works!')
    }
  }
</script>

导出默认值{
名称:“应用程序”,
创建(){
l(“它起作用了!”)
}
}

在main.js中,您在哪里定义了
window.l
?它应该在其他地方吗?在另一个Vue文件中使用l('test')会给出未捕获的引用错误:在eval(webpack)中未定义l-internal:///67:4)反对。(即使是很长的表单(尽管我们不希望这样)也给出了未捕获的TypeError:window.l不是一个函数。我将它放在public/index.html中并重新启动服务器,它在vue文件中工作。非常感谢您提供的详细答案,包括“嘿,为什么我必须编写这个或vue?”(您了解我的想法)和替代解决方案(很棒!).你太棒了!
<script>
  export default {
    name: 'app',
    created () {
      l('It works!')
    }
  }
</script>