2017-08-07 55 views
0

main.js有這個代碼如何將console.log綁定到vue.js中的「l」?

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

這在非Vue公司的應用程序的工作原理。但是,當從Vue操作/方法調用

l("test") 

,它抱怨它沒有被定義。

這怎麼能工作?

推理:需要輸出一些調試數據,輸入儘可能少。

+0

你在哪裏定義'window.l'? – lilezek

+0

in main.js 它應該在別的地方嗎? –

回答

1

當你想與全球級的功能添加到Vue公司,你應該一般使用混入插件

在接下來的例子,我假設你正在使用VUE-CLI與完整的WebPack模板。此外,我們將使用App.vue作爲一個實際的參考,但可以應用同樣的原理其它部件......


混入

創建具有下列命名log.js(在mixins文件夾)一個mixin代碼:

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,這就是全部!」嗯......這實際上是如何Vue公司的設計。爲了提供全球性的功能(由所有組件共享),你必須添加靜態屬性的Vue對象或原型屬性Vue.prototype)可通過thisVue實例中訪問。


編輯

我剛纔想到的替代解決方案...

您可以編輯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> 
+0

非常感謝您的詳細解答,包括「嘿,爲什麼我必須寫這個或Vue 「(你讀了我的想法)和另一種解決方案(太棒了!),你搖滾! –

0

像這樣分配console.log。

window.l=console.log; 
+0

使用 l('test')在另一個Vue文件中給出 Uncaught ReferenceError:l未在eval(webpack-internal:/// 67:4) 處定義 。 ( 即使是長形式(儘管我們不希望這樣)給Uncaught TypeError:window.l不是函數 –