CodeQL documentation

Arrow method on Vue instance

ID: js/vue/arrow-method-on-vue-instance
Kind: problem
Security severity: 
Severity: warning
Precision: high
Tags:
   - quality
   - reliability
   - correctness
   - frameworks/vue
Query suites:
   - javascript-security-and-quality.qls

Click to see the query in the CodeQL repository

The Vue framework invokes the methods of a Vue instance with the instance as the receiver. It is however impossible to perform this binding of instance and receiver for arrow functions, so the this variable in an arrow function on a Vue instance may not have the value that the programmer expects.

Recommendation

Ensure that the methods on a Vue instance can have their receiver bound to the instance.

Example

The following example shows two similar Vue instances, the only difference is how the created life cycle hook callback is defined. The first Vue instance uses an arrow function as the callback. This means that the this variable will have the global object as its value, causing this.myProperty to evaluate to undefined, which may not be intended. Instead, the second Vue instance uses an ordinary function as the callback, causing this.myProperty to evaluate to 42.

new Vue({
  data: {
    myProperty: 42
  },
  created: () => {
    // BAD: prints: "myProperty is: undefined"
    console.log('myProperty is: ' + this.myProperty);
  }
});

new Vue({
  data: {
    myProperty: 42
  },
  created: function () {
    // GOOD: prints: "myProperty is: 1"
    console.log('myProperty is: ' + this.myProperty);
  }
});

References

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy