0

I cannot for the life of me figure this out. I have what seems like a super simple block of code, instantiating a new Vue object hooked to a div with id providers.

const app = new Vue({
    el: '#providers', 
    data: {
        providers: []
    },
    created: () => {
        console.log(this);
    },
})

For some reason, when I call console.log(this) in created, it's returning "Window {window: Window, self: Window, document: document, name: "", location: Location, …}"

I'm running Vue 2.6.12. Can anyone help me resolve this issue?

I can't access any of my data in my lifecycle commands because of this.

Estus Flask
  • 150,909
  • 47
  • 291
  • 441
kdsprogrammer
  • 232
  • 1
  • 11

1 Answers1

3

I think the problem is in the arrow function =>: it does not have its own bindings to this or super, and should not be used as methods (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).

To bind this to a method use function long or short notation.

Long notation:

const app = new Vue({
    el: '#providers', 
    data: {
        providers: []
    },
    created: function () {
        console.log(this);
    },
})

Short notation:

const app = new Vue({
    el: '#providers', 
    data: {
        providers: []
    },
    created() {
        console.log(this);
    },
})
Konstantin
  • 301
  • 1
  • 2