Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use normal javascript file in vue component?

Tags:

vue.js

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

like image 692
xetra11 Avatar asked May 18 '26 05:05

xetra11


1 Answers

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.

like image 77
aBiscuit Avatar answered May 20 '26 22:05

aBiscuit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!