0

I have a simple component that have a template that contains just a Box, the box won't be rendered till showBox is true (it strats as false in data).

    <template>
  <div  v-if="showBox" class="Sbox" > 
  </div>
</template>

i have this timeout that controls the showing of the box after a (delay) time -delay is a number/prop. this code uses function syntax with setTimeout and it doesn't work, the box never shows up.

mounted(){
     setTimeout(function(){
      this.showBox = true
      console.log("box shows",this.showBox)},this.delay)
      }

But after i used the arrow syntax it worked, and that's weird because as i know there is no difference between the two.

   mounted(){
  setTimeout(()=> {
  this.showBox = true
  console.log("box shows",this.showBox)},this.delay)
  }

the app can be viewed at :Box component

Abdoun abdou
  • 41
  • 1
  • 6

1 Answers1

1

it's about "losing this". Arrow functions retrieve this from the lexical scope, but not in function or function expression. In your case, you can create a "function wrapper", or use func.bind(obj)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

charmful0x
  • 155
  • 9