When looking to enhance Vue with global-level functionalities, it is recommended to utilize mixins or plugins.
In the following examples, assuming you are utilizing vue-cli with the complete webpack template. The reference point will be App.vue
, but the same principles can be applied to other components...
Mixins
Create a mixin called log.js
(within a folder named mixins
) with this code:
export default {
methods: {
l (...args) { // rest parameters
console.log(...args) // spread operator
}
}
}
In App.vue
, import the mixin and use it:
<script>
import log from './mixins/log'
export default {
name: 'app',
mixins: [log],
created () {
this.l('Foo', 'Bar') // Foo Bar
}
}
</script>
Plugins
Create a plugin named log.js
(within a folder named plugins
) with the following code:
export default {
install (Vue, options) {
Vue.prototype.$l = console.log.bind(console)
Vue.l = console.log.bind(console)
}
}
In your main.js
, declare your global plugin:
import log from './plugins/log'
Vue.use(log)
In App.vue
, import Vue
and use the plugin:
<script>
import Vue from 'vue'
export default {
name: 'app',
created () {
this.$l('Foo') // Foo
Vue.l('Bar') // Bar
}
}
</script>
You may wonder: "Why do I need to write this
or Vue
? I just want to write l
", that's all!". This is how Vue is designed. To provide global functionalities shared by all components, static properties must be added to the Vue
object or prototype properties (Vue.prototype
) accessible through this
in Vue
instances.
EDIT
An alternative solution came to mind...
Edit your index.html
to include this:
<script>
var l = console.log.bind(console)
</script>
To avoid ESLint errors, edit your .eslintrc.js
file to reference the new global variable:
globals: {
l: true
}
The contents of the file should look like this:
// http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
globals: {
l: true
},
env: {
browser: true,
},
extends: 'standard',
plugins: [
'html'
],
rules: {
'arrow-parens': 0,
'generator-star-spacing': 0,
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}
Restart your dev server. Now, you can use l
in your code:
<script>
export default {
name: 'app',
created () {
l('It works!')
}
}
</script>