0

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.

JustAG33K
  • 1,403
  • 3
  • 13
  • 28
mustafa00
  • 751
  • 1
  • 7
  • 28

1 Answers1

1

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/.

tscpp
  • 1,298
  • 2
  • 12
  • 35
  • I wrote this: `const getPos = (col, row) => {return new Point(tiles.x + col*(this.size), tiles.y + row*(this.size)); };` and used here: `var p = getPos(pawn.col, pawn.row);` but got an error: `TypeError: getPos is not a function` – mustafa00 Jul 01 '22 at 11:57
  • 1
    Ok, I put this lambda function above `var p = getPos(pawn.col, pawn.row);` and it works. Thanks for clarification! – mustafa00 Jul 01 '22 at 12:01