Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

374
Views
Why can't I access data() using 'this' directly?

I work on Vue2 app. What I have noticed is sometimes I can't access elements stored in data() using this directly in my code. What I mean by that is that sometimes I need to assign this... to a variable inside a method to make it work instead of simply refer to data element by this.

I created reproducible example here: https://codesandbox.io/s/vue-2-playground-vuex-drag-and-snap-to-tiles-this-usage-trhd72?file=/src/components/ZimModel.vue

Please take a look at method addRegals(). I used this.size everywhere in this method but what I got in console is this error:

[Vue warn]: Error in callback for watcher "regalsTotalNumber": "TypeError: this is undefined"

I don't get why there's an error if I simply refer to data() element using this. To make my code work you need to uncomment code in this method (and comment not working lines). It all starts with assigning data element to variable:

var size = this.size;

I don't understand why I need to make a variable and assign this.size to it instead of explicitly using this in my method. Same situation with var tiles = this.thetiles in the same method (I also need to assign it to var to make it work in this method).

Method addRegals is triggered in watcher. Maybe here is a problem?

PS. Please type '120' as length, '55' as width in input fields (give it a few sec to show the grid on a screen), then type some number in 'Regals number' field.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have defined a local function named getPos inside the addRegals method. The only problem is that getPos does not share this with addRegals. However, when you declare the variable, it is available in the getPos closure.

The solution would either be to make getPos a local lambda function or make it a method.

You can read more on this in Javascript here: https://www.freecodecamp.org/news/the-complete-guide-to-this-in-javascript/.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!