Loading a Javascript file into a Vue component

Hi all -
I don’t know if this is possible, but I have a custom third party JavaScript file that I would like to use in my Vue component.

I have tried the following:

  1. Added a script tag to the body of my index.html and tried accessing the code in the mounted hook of my Vue component.
  2. In the mounted hook of my Vue component, creating a script element first (although this is a localized version of #1):
    let myScript = document.createElement( 'script' );
    myScript.setAttribute( 'src', './static/js/custom.js' );
    document.body.appendChild( myScript );
  1. Instead of placing the JavaScript file in the public directory, I’ve also tried static. I know both locations are ignored by webpack and just copy the file.
  2. Tried using both relative paths and absolute paths
  3. Tried something like the following in my Vue component to an epic fail:
    import * as custom from '/static/js/custom.js';

My Ionic Info dump:

Ionic:

   Ionic CLI       : 6.17.1 (C:\Users\Matt\AppData\Roaming\npm\node_modules\@ionic\cli)
   Ionic Framework : @ionic/vue 6.2.1

Capacitor:

   Capacitor CLI      : 4.0.1
   @capacitor/android : not installed
   @capacitor/core    : 4.0.1
   @capacitor/ios     : not installed

Utility:

   cordova-res : not installed globally
   native-run  : 1.6.0

System:

   NodeJS : v14.17.3 (C:\Program Files\nodejs\node.exe)
   npm    : 6.14.13
   OS     : Windows 10

I’m grabbing at straws now. Be kind, as I’m not an expert web developer. I’m not quite sure Ionic Vue is the correct post location and would be happy to locate it somewhere else.

Regards,
Matt

Hi

Also olease be gentle with as I am not a vue user, but can you postvthe errors/behavior u see per eachnoption?

And can you share which js file it is and/or content?

Option 2 imho is a no no. Too hacky

Hi all -

I have solved my issue. #1 was indeed correct. For those of you wanting the same thing, I will outline the solution. First, add your custom JavaScript file to your index.html:

  <body>
    <div id="app"></div>
    <script src="<%= BASE_URL %>js/custom.js"></script>
  </body>

Next, place a variable in the data section of your component:

  data ( ) {
    return {
    myVar: null,
    }
  },

Followed by the code in the mounted hook:

  mounted( ) {
    this.myVar = new <custom object instantiated here>
  }

@Tommertom, thank’s for your reply. Unfortunately, I cannot share this particular JS file. And not having code to look at probably caused others to pass on by.

I can access properties of the custom object, but still have issues with calling methods in the custom object. But, that is another issue for another post.

Matt