chickens
chickens

Reputation: 22314

How to run a js code after vuejs render html changes

I am using a jquery date picker tool. But it is inside a v-if. When I toggle it on and off if I write this code it does not work.

showdatepicker:function(){
    this.datepicker= true;
    $(".jquery-date-picker").datepicker();
}

Because when $(".jquery-date-picker").datepicker(); runs vue still did not rendered html and added my datepicker input. But if change it to:

showdatepicker:function(){
    this.datepicker= true;
    setTimeout(function(){$(".jquery-date-picker").datepicker();},0);
}

It works. Because runs it after html render.

My question: is setTimeout a guaranteed way to do it after html render. Is there a proposed way in vuejs to do this right. I couldn't find any answer from my google and stackoverflow searches.

Upvotes: 0

Views: 834

Answers (2)

Josh
Josh

Reputation: 956

You can use nextTick which will call a function after the next DOM update cycle.

this.datepicker = true;

Vue.nextTick(function () {
  $(".jquery-date-picker").datepicker();
})

And here is it's page in the documentation VueJS Docs

Upvotes: 2

xdrm
xdrm

Reputation: 399

Vue features triggers, in your case the mounted() function could be used. This articles describes how to use it and the whole Vue hook timeline : https://alligator.io/vuejs/component-lifecycle/

A stackoverflow explanation : Vue JS mounted()

Upvotes: 0

Related Questions