I have a file called Helper.js which holds functions which use some libraries.
Now I have a TestComponent.vue file and want to use this helper functions. How can I inject this functionalities?
I tried to use the libraries used in Helper.js directly in the Components block but it seems that vue is running before any library is included regardless of the order of the index.html's tags.
How can I use the .js file or other libraries
2 Answers 2
In order to use additional libraries or helper functions inside Vue templates you can simply import them into the script tag of the template:
TestComponent.vue
<template>
<!-- template markup -->
</template>
<script>
import Helper from 'relative/path/to/Helper.js'
// or just a helper function (that should be exported accordingly
import { helperFunction } from 'relative/path/to/Helper.js'
export default {
name: 'TestComponent'
// component data, methods, etc are now able to use imported variables
}
</script>
This way you can use any additional JS inside your component. Webpack will include it in the bundle. Though, it might become uncomfortable to maintain or repeat imports if library is used in many components. In this case, it is possible to define the library on Vue prototype inside the main application file where Vue instance is created, which will make it accessible from any component.
import moment from 'moment';
Object.definePrototype(Vue.prototype, '$moment', { value: moment });
Please, follow the article for detailed explanation and better practices.
Comments
The correct answer is:
First you need to import the library, so you can define Property.
import moment from 'moment';
Object.defineProperty(Vue.prototype, '$moment', { value: moment });
Please note that you should use defineProperty instead of definePrototype.
This way you can call into your Vue something like this: this.$moment();
<script src="js/build.js"></script>but did not worked