繁体   English   中英

如何在vue.js中将console.log绑定到“ l”?

[英]How to bind console.log to “l” in vue.js?

main.js有此代码

window.l = function () { }
try {
  window.l = console.log.bind(console)
} catch (e) { }

在非Vue应用中有效。 但是,打电话时

l("test")

从Vue动作/方法中,它抱怨没有定义。

那怎么办?

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

当您要将全局级功能添加到Vue时,通常应使用mixinsplugins

对于下一个示例,我假设您使用带有完整webpack模板的vue-cli 此外,我们将使用App.vue作为实用参考,但是您可以将相同的原理应用于其他组件...


混合蛋白

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

export default {
  methods: {
    l (...args) { // rest parameters
      console.log(...args) // spread operator
    }
  }
}

打开App.vue ,导入您的mixin并使用它:

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

  export default {
    name: 'app',
    mixins: [log],
    created () {
      this.l('Foo', 'Bar') // Foo Bar
    }
  }
</script>

插件

使用以下代码创建一个名为log.js的插件(在plugins文件夹中):

export default {
  install (Vue, options) {
    Vue.prototype.$l = console.log.bind(console)
    Vue.l = console.log.bind(console)
  }
}

打开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>

您可能会说:“嘿,我为什么要写thisVue ?我只想写l ,仅this Vue !”。 好吧...这实际上就是Vue的设计方式。 为了提供全局功能(由所有组件共享),您必须将静态属性添加到Vue对象或原型属性Vue.prototype ),可以在Vue实例中通过this 属性访问this 属性


编辑

我刚刚想到了替代解决方案...

您可以编辑index.html来添加以下内容:

<script>
  var l = console.log.bind(console)
</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>

这样分配console.log。

window.l=console.log;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM