Vue.js: In a third-party library, the reference to "this" is coming back as "undefined"

My third-party script contains code in the following format

(   function initialMethod(scope, factory) {
        // 'scope' is undefined when used in Vue
        // but it works fine in React and Angular
    } (this, function function1(param1) {
              .....
             }       
      )          
    ....    
    function MyMethod() {....}
    ....
)

To import a method from this third-party library, I use the following syntax

import {MyMethod} from 'ThirdPartyScript'

While this works perfectly in React or Angular, it fails in Vue. The "scope" or "this" gets undefined. Here's a sample Vue code snippet:

<template>
    <div id="app">
       <p>Hello</p>
    </div>
</template>


<script>
    import {MyMethod} from 'ThirdPartyScript';

    export default {
        name: 'app',        
        created: function () {
          this.initApp();
        },
        methods: {
            initApp: function () {                
                //const myResult = MyMethod();
            } 
    }
</script>

This error occurs as soon as I include the "import" statement for the third-party library, which causes the execution of the "initialMethod" function due to the parentheses indicating execution.

Why does this behave differently in Vue? Do I need to configure something differently while using Vue?

Environment info

I used Vue CLI to set up my project, with the following versions mentioned in package.json:

dependencies": {
    "core-js": "^2.6.5",
    "vue": "^2.6.10",        
},
"devDependencies": {
    "@vue/cli-plugin-babel": "^3.11.0",
    "@vue/cli-plugin-eslint": "^3.11.0",
    "@vue/cli-service": "^3.11.0",
    "babel-eslint": "^10.0.1",
    "eslint": "^5.16.0",
    "eslint-plugin-vue": "^5.0.0",
    "vue-template-compiler": "^2.6.10"
 },

Update

If I change the "this" in the third-party library to "window," I make some progress, but now I encounter an error on the following call:

const myResult = MyMethod();

The error message states "Object(...) is not a function" for "MyMethod."

Answer №1

After some troubleshooting, I was able to resolve the issue at hand.

This particular problem seemed to only occur when I had a local version of the library within my project directory (specifically placed under "scripts" alongside other JavaScript utility files).

Upon introducing the library via package.json/package-lock.json and executing the "npm install" command, the library was successfully loaded without any further errors.

package.json

"dependencies": {
    "theLibrary": "https://.......",
    "core-js": "^2.6.5",
    "vue": "^2.6.10",
    "vue-router": "^3.1.3"
},

package-lock.json

"dependencies": {
    ......
    "theLibrary": {
        "version": "https:.....",
         "integrity": ".....
    },
    ......
}

npm command

npm install theLibrary 

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

Working with AngularJS's $q promise and socket.io

I am interested in creating an angularJS promise that can work seamlessly with socket.io. Currently, I have a callback function set up to handle the response like this: function request(event, data, callback) { socket.emit(event, data); socket.on( ...

The masonry plugin overlays images on top of each other

I have gone through similar questions but haven't found anything that applies to my specific case. Following an ajax call, I am adding li elements to a ul $.ajax({ url: 'do_load_gallery.php?load=all' }).done(function(result) { ...

Is there a way to showcase the content of a text file in a sequential manner using Javascript/AJAX?

I am attempting to retrieve text data from a server file and exhibit it within a specific division on my website. Check out the AJAX/Javascript code I have been working with: <body onload="loadXMLDoc()"> <script> function loadX ...

Dynamic sidebar that adheres to the content and is placed alongside it using JavaScript

I am in need of creating a sticky sidebar that will float beside my content column. The purpose of this sidebar is to contain jump links on the page, similar to what can be seen on this page, but with the navigation buttons positioned directly next to the ...

Express.js: Initial Request Fails to Retrieve Set Cookie

In my Express.js application, I am facing an issue where setting a cookie in one middleware function results in it being undefined when attempting to access it in the following middleware function on the initial request. Strangely, on subsequent requests, ...

The clash between two jQuery plugins featuring identical function names

I have encountered a dilemma while working on a large website that includes two conflicting jQuery plugins for autocomplete functionality. The first plugin is jquery.autocomplete.js (not part of jQuery UI) which defines the autocomplete function like this ...

Leveraging TipTap.dev for building a joint editing platform -

I have integrated the collaboration feature from tiptap.dev into my NextJS application. Initially, I used their CLI command for the Hocuspocus server which worked well on port 1234 locally and synchronized text editing across browsers seamlessly. However, ...

Utilizing OrientDB in a SailsJS Application: A Step-by-Step Guide

I'm diving into the world of NodeJS and SailsJS after working with Rails and PHP. I'm interested in integrating SailsJS with OrientDB, but I'm unsure of the best approach to take. I've come across two options so far, but the available ...

Choose an element that has been generated dynamically using jQuery

Here is an example HTML table to work with: <table id="#myTable"> <tr id="#row123"><td>Content</td></tr> </table> To insert a new row using jQuery, you can use the following code: $('#myTable').prepend(&ap ...

customizing highcharts title within a popup window

Is there a way to dynamically set the title of a Highcharts chart from an element? Check out my code snippet below: $(function () { var chart; $('#second-chart').highcharts({ chart: { type: 'bar' }, subtitle: { ...

Redirecting script upon successful connection detection

I have created a script that checks for internet connectivity using an image, and redirects if internet is available. However, the issue is that it caches the images, leading to attempts to load them even when offline. Is there a different approach I can ...

Interested in gaining knowledge on how to define basic properties on the model within Angular.JS?

As I dive into the demos on the angular.js website, one aspect that caught my attention is the lack of explicit model/properties definition compared to other frameworks like durandal. For instance, how can we access the property "yourName" in a particular ...

AngularJS dropdown with multiple selections within a Bootstrap modal

Being new to AngularJS, I apologize for asking this question in advance. I am utilizing Angular bootstrap modal from the following link: https://angular-ui.github.io/bootstrap/ and multiple select dropdown list from: https://codepen.io/long2know/pen/PqLR ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

Transform the string response in a websocket message into JSON format

When receiving a websocket message, I often encounter a response in the form of a string like this: odds.1:[{"id":1,"marketType":10,"name":"Double chance","status":"HandedOver","specifiers":"","Outcomes":[]},{"id":2,"marketType":11,"name":"Draw no bet", ...

Strip the CSS styling from an image (the CSS being included in the generated code)

I need to remove the CSS styling from an image, but I can't modify the generated code where it's coming from. My actual code looks like this: <div class="bubble"> <img id="one" src="/static/webupload/MyronArtifacts/images/descarga.png ...

Setting up the react-ultimate-pagination component

I've been experimenting with the react-ultimate-pagination package available at: https://github.com/ultimate-pagination/react-ultimate-pagination My goal is to configure it in a way similar to their basic demo showcased here: https://codepen.io/dmytr ...

Create objects in the gallery

I recently developed a React Material-UI component using Typescript: <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start"> <Grid item xs={5}> <B ...

Utilizing a combination of Vue, Vuex, and GSAP Animation to effectively store new DOM elements

I'm currently working on a Vue project and trying to figure out a way to store DOM elements in the application state for animation with GSAP. One issue I encountered is the timing conflict between when the DOM is ready (for using document.querySelect ...

Issue encountered at 'site construction' phase: failure in build script with exit code 2

I am a novice and struggling to solve this error. I have attempted to fix it by adjusting the deploy settings, but I can't seem to resolve this compilation error. The syntax errors are overwhelming, and I'm not sure if there is something crucial ...