1

I have created frontend application with Vue Js. I want to integrate one native javascript file into the Vue component.

The native js file contains multiple util functions. I want to call those functions from my Vue component.

Native js file util.js

var helper = function(t) {
                var u = 'product',
                    A = 'version',
                return {
                    buildHelpUrl: function(a, b, c) {
                                   return "http://"
                                 }
               /* Snippets */
             }

I tried following way to import in my native js file into .vue file

Case 1: import OTHHUrlBuilder from '@/util.js';
Case 2: import * as urlbulider from '@/util.js';

Nothing worked. Please help me to properly import and use the functions available in the native js files.

2
  • Are you exporting the helper function from util.js file? Commented Jan 10, 2022 at 6:17
  • You can't import anything from non-modular JS. You need to make it a module first. Commented Jan 10, 2022 at 6:47

1 Answer 1

2

First export all your functions you need to your .vue file.

Exemple on your .js file :

  const funcAdd = (a, b) =>  {
   return (a + b)
  }

  const funcSub = (a, b) =>  {
    return (a - b)
  }

  export { funcAdd , funcSub }

And then on your .vue file you can import all the exported functions.

On your .vue file :

  <script>

  import { funcAdd , funcSub } from '@/util.js'

 ...

If you have only one function function, you can use export default

On your .js file

const helper = (t) => {
          var u = 'product',
                    A = 'version',
                return {
                    buildHelpUrl: function(a, b, c) {
                                   return "http://"
                                 }
               /* Snippets */
             }

    export default helper

and on your .vue file

    import helper from '@/util.js'

Sign up to request clarification or add additional context in comments.

2 Comments

It works fine as expected. One more scenario, Suppose inside the function funcAdd which also uses another js file function means where I need to import that js file
If you want to use a function that is in one .js file in another .js file, you can do the same process, take a look at this demo. Here is the code import isANumber from './tools/isANumber'; const funcAdd = (a, b) => { if (isANumber(a) && isANumber(b)) { return a + b; } else { return null; } }; export { funcAdd };

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.