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.