Bringing in an outside JavaScript document into VueJS

I'm having an issue with Vue CLI where I need to import a JavaScript file from a different server. Unfortunately, no matter what I try, I keep encountering the same error message as indicated below.

https://i.sstatic.net/ssFy2.png

Does anyone have a solution to this problem? How can I successfully import an external JS file?

Below is the code snippet of my Vue file:

<!-- Use preprocessors via the lang attribute! e.g. <template lang="pug"> -->
<template>
  <div id="app">
    <p>Test</p>

    <button @click="doSomething">Say hello.</button>
  </div>
</template>

<script>
import TestFile from "https://.../src/TestFile.js";

export default {
  data() {
    return {
      message: "<h1>anything</h1>"
    }
  },
  async mounted() {
    await TestFile.build();
  },
  methods: {
    doSomething() {
      alert(message);
    },
  },
};
</script>

<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style>
</style>

Answer №1

When it comes to using external modules from a URL, the traditional import method won't work. However, there is a clever workaround that allows you to utilize scripts directly from the URL.

It's akin to incorporating a script from CDNJS. The key is to create an element and then append it to the document's script.

An effective approach would be to leverage a mounted lifecycle hook to handle this process.

Here's an Illustrative Example of Importing FontAwesome CDN Script:

mounted() {
      let fontAwesome = document.createElement('script')
      fontAwesome.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js')
      document.head.appendChild(fontAwesome)
    },

This method of registering a script will grant your functions access within the global object window.

For instance, you can now easily tap into various properties of FontAwesome like so:

window.FontAwesome.config

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method to delay the computation in meteor.helper until after a re-computation is triggered by a change in dependency within the template.autorun

I keep encountering a common error whenever a reactive variable is updated: Exception in template helper: Error: $in needs an array at Error (native) at Object.ELEMENT_OPERATORS.$in.compileElementSelector (http://localhost:3000/packages/minimongo. ...

Creating a JSON object in JavaScript using an array

Can anyone assist me with the following code snippet for formatting the current month? var monthNames = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set&apos ...

My project involving Node.js is currently experiencing a roadblock with the 'starting node.js' phase, resulting in an

As I delve into a tutorial for the MERN stack, here is the current code snippet that I have been working on: const app = express(); //setting up to send out requests app.use(bodyparser.json({ limit: "30mb", extended: true })) app.use(bodyparser.u ...

Innovative User Handle Generation using Firebase in a React/Javascript Environment

My goal is to create new users using Firebase authentication and store their information in Firestore. Everything was going smoothly until I encountered the challenge of generating unique usernames. What would be the most effective approach to tackle this ...

directive unit testing unable to access isolatedScope as it is not recognized as a valid

Currently, I am in the process of conducting unit tests on a directive that was previously created. For my initial test, I simply want to verify a specific variable within the scope of the directive. However, whenever I attempt to execute the method isola ...

Create a personalized attribute for an element using Jquery

I am attempting to utilize jQuery to add a custom attribute to my element: $('.map-areas-div').rand(numElements).each(function(){ $(this).attr('element_id',4); }); However, I have noticed that the "element_id" attribute is not p ...

What are the available search options in the MarkLogic Search API to limit keyword searches from including specified values within JSON properties?

Is there a way to limit the MarkLogic search API keyword search so it does not include specific JSON property values? For example, can I search for keyword 'x' in all properties of JSON documents except for those with values of 'p', &ap ...

Excessive KeyDown Events being generated from a single key press

Currently, I am working on detecting a keydown event for the spacebar in my JavaScript file and executing certain logic based on it. In my HTML code, there is a "compose" button that reveals the message-container when clicked. The functionality I aim to a ...

What is the process for utilizing handlebars within erb tags?

Is there a way for me to submit a form with a hidden field tag that retrieves its values from my vue instance? Here is an example: <%= form_for @post, new_data_path %> <%= f.hidden_field :data, value: {{ data }} %> <%= f.submit 'C ...

Trouble with updating image using url() function in JavaScript/HTML (SIMPLE FIX)

Seems pretty straightforward, but I feel like I'm overlooking something here. I am trying to swap an image defined in HTML like this: <a href="properties-single.html" class="img" id="albumPhoto1" style="background-image: url(images/work-1.jpg);"&g ...

Issue: The child component is not being displayed in a nested route in React

Utilize React nested routes with Home as the parent and News as the child. The directory structure consists of a "src" folder at the root containing a "pages" folder which further contains "Home" and "News" folders. Inside the "News" folder, there is an in ...

Code snippet of sails js, as seen on the homepage

I'm currently exploring sailsjs and trying out a simple example from their main page, but I keep encountering this error: TypeError: socket.request is not a function socket.request('/user', {}, function(users){ console.log(users); }); This ...

What is the alternative method of sending a POST request instead of using PUT or DELETE in Ember?

Is there a way to update or delete a record using the POST verb in Ember RESTAdapter? The default behavior is to send json using PUT or DELETE verbs, but those are blocked where I work. I was wondering if there's a way to mimic Rails behavior by send ...

The best way to horizontally arrange card-images side by side in react native

Recently delving into the world of react native, I encountered an issue with aligning card images side by side using react-native-elements. My goal is to have two rows on phones and three rows on tablets. However, despite setting the flex-direction to row ...

Using jQuery, eliminate a single value from all drop down options

I am facing an issue where I have multiple drop-downs with the same values. When a user selects "Lunch" from one of the drop-downs, I need to remove "Lunch" from the rest. Below is my code: Frontend code: <?php for($i=1; $i<=7; $i++) {?> <se ...

What term is used to describe this in recursion?

I am trying to understand the concept of reversing a linked list and I stumbled upon a peculiar scenario in which a recursive function doesn't "return" but instead just calls itself. It seems that the function processes data backwards after the recurs ...

next.js experiencing hydration issue due to using div tag instead of main tag

I've come across an issue with hydration in NextJS and after debugging, I discovered that using the div tag instead of the main tag is causing this problem. The error message I'm receiving https://i.sstatic.net/aIKkO.jpg Here is the code snippe ...

Attempting to toggle the visibility of div elements through user interaction

I'm having an issue with click events on several elements. Each element's click event is supposed to reveal a specific div related to it, but the hidden divs are not appearing when I click on the elements. Any help in figuring out what might be g ...

Error: null does not have the property 'renderView' to be read

My goal is to set up a main page in React.js with two buttons: Option 1 and Option 2. Clicking on Option 1 should redirect the user to the Main1 page, while clicking on Option 2 should lead them to Main2. It seems straightforward, but I am encountering the ...

"Discover the method to access values within an associative array or object in an Ember template by utilizing a

When working with Ember, the traditional syntax for looking up array values by key is to use the .[] syntax. For example: {{myArray.[0]}} However, I have encountered an issue when trying to perform a lookup on an associative array. Even though I have a s ...