0

I have a vue component with following structure:

   export default{
     name: '',
     data: function () {
        return {
           var1 :{},
           var2 : {},
           ...
        }
     },
     created: function () {
         this.methodName1()
     },
     methods: {
        methodName2: function () {
           var context = this

           rp(options).then(function () {
              context.methodName1()
              return null
           }).catch(function (err) {
              console.log(err)
           })
       },
       methodName1: function () {
             //function body
       }
   }

My doubt is why this.methodName1 gives undefined where as

    var context = this; 
    context.methodName1 

works perfectly fine inside the methodName2?

Why do we need to reference the this variable especially to modify the DOM elements?

  • 1
    is your question why you can not write `this.methodName1()` in `then` callback in methodName2? – Max Sinev May 30 '18 at 19:30
  • Yes, not only in callback outside callback too –  May 30 '18 at 19:40
  • VueJS holds your hand for `methods`, rewiring their `this` into more sophisticated object. But it doesn't do this for code inside the methods. You'd use fat arrow functions - or store context explicitly, as you did in that snippet. – raina77ow May 30 '18 at 19:46
  • Ok. I understood a bit but my confusion still lies at 1. why are we storing reference to this in another variable? 2. why direct use of this doesn't work? (`var context = this; context.methodName1` isn't it same as using `this.methodName1()`) –  May 30 '18 at 20:00

1 Answers1

-1

Look closely at the Lifecycle-Diagram in official docs. You're trying to run this.methodName1() in created which is hooked before your methods, meaning you're trying to run a method that has not been attached yet.
mounted is where all your methods are already available.
Change:

created: function () {
     this.methodName1()
},

to

mounted: function () {
     this.methodName1()
},

and you should be good to go.

tony19
  • 125,647
  • 18
  • 229
  • 307
6bytes
  • 5,858
  • 9
  • 37
  • 42
  • 1
    `created` hook is ok for accessing methods and component data, `mounted` is neccessary if you want to access DOM or manipulate child components. Your answer is incorrect. – Max Sinev May 30 '18 at 20:04