2

Take a look at the following simple component example 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'm trying to understand why this is undefined in the two() function when it's called from the one() function. Both functions are returned in setup(), so I would expect them to both have access to this.

This being said, how do I then get a reference to the component instance of this inside my two() function?

1
  • 1
    Just don't rely on this with composition API. Commented Jul 3, 2021 at 7:20

1 Answer 1

3

I would imagine Vue still has to obey the rules of Javascript. When an Event handler is invoked, typically it's in the context of the object receiving the event. In this case, one() is invoked with this bound to the Proxy for the <a> element.

However, two() is invoked specifically without a context (ie: two() instead of someobject.foo()). Which means this will be undefined.

I'm not terribly familiar with Vue, but I imagine it doesn't do automatic method binding so as not to require you to pay for things you don't use.

Since this is bound correctly in one(), you can actually call two() as a method of this instead of as a bare 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>
Sign up to request clarification or add additional context in comments.

1 Comment

I imagine it doesn't do automatic method binding so as not to require you to pay for things you don't use - it does but only for functions specified in methods, which is legacy API.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.