What Causes the Undefined Value of "this" in Vue 3 Functions?

Here is a basic example of a component in Vue 3:

<script>
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'Test',
  setup(){
    return{
      one,
      two
    }
  }
})

function one(){
  console.log(this) //<-- Proxy{}
  two()
}

function two(){
  console.log(this) //<-- undefined
}
</script>
  
<template>
  <a href="#" @click.prevent="one()">Start</a>
</template>

I am puzzled as to why this is showing up as undefined in the two() function when it is called from the one() function. Since both functions are returned within the setup(), I would assume they would both have access to this.

So, how can I obtain a reference to the component instance with this inside my two() function?

Answer №1

Vue probably adheres to the rules of JavaScript. When an event handler is triggered, it usually operates within the context of the object that receives the event. In this scenario, one() is called with this referring to the Proxy for the <a> element.

On the other hand, two() is invoked without a specific context (i.e., just two() instead of someobject.foo()), resulting in an undefined value for this.

My knowledge of Vue is limited, but I assume it doesn't automatically bind methods to avoid unnecessary overhead for unused features.

Given that this is properly bound in one(), you can invoke two() as a method of this rather than a standalone function:

<script>
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'Test',
  setup(){
    return{
      one,
      two
    }
  }
})

function one(){
  console.log(this) //<-- Proxy{}
  this.two()
}

function two(){
  console.log(this) //<-- Proxy{}
}
</script>

<template>
  <a href="#" @click.prevent="one()">Start</a>
</template>

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 ways can we implement identification features in Flutter Web applications, such as adding an ID or name property?

While developing a Flutter Web application, I am exploring a Web-UI-Testing framework that is Selenium-based. Unfortunately, I am struggling to locate an HTML element that represents a specific flutter widget by its id or name attribute. The widget key doe ...

Steps for importing a React component as an embedded SVG image

I have developed a SVG component in React by converting an SVG file to a React component using the svg-to-react cli tool. In order to load and display additional svg files within this component, I am utilizing the SVG image tag as demonstrated below. This ...

I encountered an issue while trying to use the vue toastification library for notifications. The error message indicated that an outdated optimize dependency was

Currently, I am encountering compatibility issues while trying to incorporate toasts into my nuxt 3 project. In the past, I utilized @nuxtjs/toast with nuxtjs 2 successfully. However, upon transitioning to nuxt 3, this module is no longer functional. As ...

Achieving VueJS reactivity by initializing a variable within the mounted function

I am facing an issue with a dynamic component that builds multiple select elements. Here is the template code: <template> <div> <b-field v-for="(key,index) in allSelects" :key="index" :label=" ...

Changing Table Cell Color with Bootstrap Based on Value

I have implemented Bootstrap tables into my project using the tables provided on this website Bootstrap Tables and I am populating data from my MongoDB to these tables. One of the fields in my table is labeled "ACTIVE" and I am looking for a way to dynami ...

Updating HTML images in real-time using a combination of Flask and Ajax

I am facing a situation similar to the one discussed in this thread: Flask+AJAX+Jquery+JINJA to dynamically update HTML Table. However, I am struggling to adapt the solution to suit my specific requirements. My objective is to automatically update the imag ...

An exclusive execution of the JavaScript function is ensured

I have a JavaScript function that I want to execute 12 times in a row. Here's my approach: Below, you'll find a list of 12 images: <img id="img1" src=""> </img> <img id="img2" src=""> </img> <img id="img3" src=""> ...

The Next.js middleware, specifically NextRequest.nextUrl.locale, will return an empty string once it is deployed

Encountering a bug in the next-js middleware The middleware function is returning a NextRequest param According to the documentation from Next.js: The NextRequest object is an extension of the native Request interface, with the following added metho ...

The limitations of Typescript types influence the program's behavior

As a newcomer to the Typescript environment, I am currently developing a test application to familiarize myself with it. However, I have encountered an issue regarding type restrictions that seems to be not working as expected. In my class, I have defined ...

Unleashing the Power of Aurelia's HTML Attribute Binding

I need to bind the "required" html attribute in my template and model. Along with passing other information like the label value using label.bind="fieldLabel", I also want to pass whether the element is required or not. However, simply using required="tr ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

Show spinner until the web page finishes loading completely

Could anyone guide me on how to display Ring.html for a brief moment until About.html finishes loading completely? I need the Ring.html page to vanish once About.html is fully loaded. As a beginner in web development, I would greatly appreciate your assist ...

Executing Ajax requests with callbacks in JavaScript/jQuery

I'm facing an issue where my functions are executing before Ajax requests (first fetching local JSON, then retrieving data from an online resource) have completed. For example, I want countTheMovies to run only after all the necessary information is ...

Stopping a NodeJs file running on an Ubuntu server

After enlisting help to install a Js script on my server, I encountered an issue where changes I made to the scripts/files were not reflected in the browser. After scouring the internet for answers for about 24 hours, I discovered that Js scripts need to b ...

Encountering a frustrating Npm error while trying to install a package, which persists in throwing

Encountering an error message while trying to run npm install npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\ node_modules\&bsol ...

Using jquery to transition an image to fade out and then reappear in a different position

There is an image in a div with the highest z-index. Upon clicking on something, the image should fade out and then fade in at a specified position below another image with the class "aaa". The current approach involves using jQuery to fade out the image ...

The functionality of Flatbutton(Input handler) appears to be malfunctioning

I am having trouble with the file uploader from Material-UI. It doesn't seem to be working properly when I try to select a file. Does anyone have any suggestions on how to handle the input from the file selector? <FlatButton icon={< ...

Live JSON sign-up feature on site

Is there a way to retrieve user email in real-time without using JSON? Currently, I am utilizing JSON for this purpose but it poses the risk of exposing emails that are stored in $resEmailsJson. Ideally, I would like to find a solution to hide all JSON $ ...

What is the process for adding elements to the parent elements that have been selected using getElementsByClassName?

Here is the JSP code snippet I'm working with: <% while(resultSet1.next()){ out.println("<p class='comm'>"); out.println(resultSet1.getString("answer_content")); ...

Analyzing objects within an array for similarities

Suppose I have an array containing objects: var arr = [ { id: 1, pt: 0 }, { id: 2, pt: 12 }, { id: 3, pt: 7 }, { id: 4, pt: 45 }, { id: 5, pt: 123 }, ]; I am looking to loop through this array (possibly using array.forEach or array.map) ...