0

So I'm learning Vue, without having ever really been a javascript programmer, I did some light Jquery, but that's about it. Mostly I've done c++ and c# where 'this' behaves much more simply.

I'm reading about this in Javascript, but I'm trying to grok just in Vue, and built a set or rules or patterns to follow in Vue. I'm not there yet from the this rules in JS

In Vue Sometimes *(like in Lifecycle Hooks) you HAVE to use a function so that 'this' is the vue page object:

mounted: function () { console.log(this); }

or in es5+

mounted() { console.log(this); }

But other times, for Vue to have a correct meaningful this, you HAVE to use an arrow function, Like when using Axios

axios.get( obj.Url + "StudentAdName=" + obj.StudentAdName ) .then(response => {// if you use a method here this is a Bad Value this.info = response.data; this.isloaded = true; }) .catch(function (error) { console.log(error); });

And I'm finding this mightily confusing, when do you have to use a function, and when do you have to use an arrow function.

I read that Functions have an implicit 'this' based on who Is calling them, and arrow function "look up" their this based on some obscure javacript rules...

But I don't know how to turn that into a set of rules to follow on when to use which.

So Far I have

Rules to Have a Valid This pointer in Vue

  1. Always call a function when writing a "lifecycle Hook" call in Vue.
  2. Always use a arrow function, something something, Axios, something something, chaos.

Alternately, as simple consistent set of patterns to have this in Vue always refer to the vue page object would be great (like how to use "that" to be right when this isn't)

Eric Brown - Cal
  • 13,058
  • 11
  • 52
  • 89
  • 1
    learn about [.bind()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) or [.call()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) you dont HAVE to use arrow functions – Lawrence Cherone Aug 20 '20 at 14:56
  • I found this, its explains teh basics of scope, but i still cant' use it to generate a list of rules when this is valid or not in Vue..: http://www.digital-web.com/articles/scope_in_javascript/ – Eric Brown - Cal Aug 20 '20 at 15:29

0 Answers0