Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the 'this' keyword in Vue

I have started to learn VueJS from scratch. I am following their official Guide. But I am stuck here: https://v2.vuejs.org/v2/guide/#Handling-User-Input

In this example...

var app5 = new Vue({
  el: '#app-5',
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    reverseMessage: function () {
      this.message = this.message.split('').reverse().join('')
    }
  }
})

..how is it that the message property is directly being accessed without any reference to the data object? If this keyword refers to the current Vue instance, shouldn't the message property be accessed like this: this.data.message?

Consider the following example:

({
  name: "John Doe",
  data: {
    message: "Hello World"
  },
  greet: function(){
    console.log("I am " + this.name);
    console.log("I have a message for you: " + this.data.message); //see here
  }
}).greet();

This is how I would have accessed a property in vanilla javascript. Can someone please make me understand what's going on behind the scenes?

like image 443
Tanmay Avatar asked Dec 19 '25 13:12

Tanmay


2 Answers

In Vue, Vue instance proxy properties of data and methods by using Proxy

like image 133
Kermit Avatar answered Dec 21 '25 01:12

Kermit


Read this: Options / Data

From that we get "The data object for the Vue instance. Vue will recursively convert its properties into getter/setters to make it “reactive”." Meaning everything in the data object property is applied directly to the new Vue. This makes thos properties available on this as getters and setters.

like image 44
gforce301 Avatar answered Dec 21 '25 03:12

gforce301



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!