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

Ways to loop through HTML elements based on certain criteria?

Issue : The v-for loop is successfully iterating and binding data in the HTML template, but there is a challenge in partially iterating it based on certain conditions. Please refer to the JSFiddle link below for a demo. Objective : In the provided demo li ...

Utilizing a function within a span element

Can anyone help me figure out what I'm doing wrong while trying to toggle between a span and an input text field using the on function? If you want to take a look, I've created a fiddle for it here User Interface <div> <span >My va ...

bxSlider adds in an empty slide after deleting an image

Whenever I click a link in my navigation, I want to remove certain images from the page. I tried implementing a solution, but now I have two empty spaces where the images used to be. How can I remove those as well? I searched on Stack Overflow for a soluti ...

Are the results displayed in a vertical array format?

Being new to this world, I would greatly appreciate any assistance! I am working with Bootstrap checkboxes and trying to print them using jQuery's window.print function. However, the issue I am facing is that the array I create from the checkboxes d ...

Mysterious source utilizing leafletView for showcasing popups within the Angular Leaflet Directive

I've been attempting to implement a pop-up window on an Angular Leaflet map using Prune Cluster, but I keep running into an error stating that 'leafletView' is an unknown provider. Despite following the examples provided on this page, https: ...

Updating or swapping images using JavaScript and HTML

I am looking to implement a feature similar to Twitter, where uploading a picture automatically updates the avatar by displaying a spinner while the new image loads. I attempted to accomplish this with the following code: <script language="javascript"& ...

How can you efficiently access the 'app' object within a distinct route file?

When using Express 4, the default behavior is to load routes from a separate file like so: app.use('/', routes); This would load routes/index.js. I am working with a third-party library that directly interacts with the app object itself. What& ...

Looking to combine cells within a table using the Exceljs library

Encountered an issue while generating a worksheet in the EXCELJS library. function save_export(){ var workbook = new ExcelJS.Workbook(); var worksheet = workbook.addWorksheet('sheet', { pageSetup:{paperSize: 9, orientation:' ...

What is the process for configuring sendmail in a node.js environment?

After setting up Sendmail on my Nginx server and configuring SMTP for sending emails in my Node.js project, I still encountered issues with emails not being sent. I tried using Sendmail directly, but I'm unsure of how to properly configure it. Here i ...

What is causing this promise to fail?

Exploring the use of promises in a code example has left me puzzled. Despite my efforts to understand promises, my initial attempt failed and only outputted "Promise didn't work". Upon closer inspection, I realized that the hide() function taking 400 ...

Issue involving retrieving keys from multiple classes in a JSON object

I am facing some difficulties with JSON and JavaScript as I am a beginner in this area. Currently, I am attempting to iterate through all the keys["name"] of this JSON data. var l = [{ "pages": [ { "name": "Scan", "elements": [ { "type": ...

Parcel js is encountering difficulties running the same project on Ubuntu

I have encountered an issue with my JavaScript project when trying to run it on Ubuntu using parcel 2 bundler. The code works perfectly fine on Windows, but in Ubuntu, I am facing errors. Despite trying various solutions like cleaning the cache and reinsta ...

Navigating an array index within a v-for loop in Vue.js

I am facing an issue with assigning colors to elements in my component using data from Vuex state. I have an array of colors in my Vuex state and I want to specify a color for each element that comes from v-for loop. // state state: { APIData: { ...

What is the best way to implement Media Queries in the Next.js application Router?

I am currently working with Next.js 13 and the App Router. Within my client component, I have implemented media queries in JavaScript to customize sidebar display for small and large screens. "use client"; export default function Feed() { co ...

Ways to streamline redundant code by creating a higher order function that accepts different parameter types in TypeScript

Recently, I've been exploring the idea of refactoring this code into a higher order function using TypeScript to enhance its cleanliness and reusability. However, I'm facing quite a challenge in getting it to work seamlessly. import { DocumentDef ...

What is the process of importing an HTML template into a Vue.js project?

I downloaded a template from the internet that I want to import into my vue project. This template includes HTML, CSS, and Javascript files of its own. How can I utilize vue-router to access the index.html file in this template without converting them into ...

"Using the check function in JavaScript to determine if a value

I have a JSON file containing data, and I am looking to create a function that extracts only the values from each object and adds them to a list. Is there a more efficient way to write this code so it can run indefinitely and continue pushing non-object v ...

The issue arises with getInitialProps as it fails to pass data to the page component while attempting to retrieve initial information and subsequently modify it using a button

I am currently working on a component located at app\page.tsx in Next.js v13.4.12, and it includes a button. My goal is to have the button trigger the handleClick function when clicked. The issue I'm facing is that the getInitialProps function ...

Stop users from saving the page in Next.js

I'm currently working on a NextJs project that involves building an editor application. I want to ensure that the editor functionality does not work when users attempt to save the page in a different format, similar to how applications like Youtube an ...

What is the best way to generate hyperlinks from data in a MongoDB database?

Looking for some assistance in setting up an online discussion forum using node.js, express & mongodb. My current challenge is creating clickable links that will redirect me to the specific page of each article stored in the database. I need to figure out ...