簡體   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