Adam Zerner
Adam Zerner

Reputation: 19238

Vue: How to re-render view midway through event loop cycle?

https://codepen.io/anon/pen/mqbaXE?editors=1010

I'd like value to display as "B" immediately after you click the button, and then display as "C" after a huge loop finishes. How can I accomplish this? Currently it never displays as "B".

In my actual application, I am running a bunch of simulations. When the user clicks "Simulate", I need to: change the text to say "Simulating...", run the simulations, and then change the text back to say "Simulate".

I've tried Vue.nextTick, vm.$forceUpdate, and setTimeout(fn, 0), but none seem to work.

HTML

<div id="example">
  <p>Value: {{ message }}</p>
  <button v-on:click="change()">Change</button>
</div>

JS

var vm = new Vue({
  el: '#example',
  data: {
    message: 'A'
  },
  methods: {
    change: change
  }
})

function change () {
  vm.message = 'B';
  
  setTimeout(function () {
    for (var i = 0; i < 2000000000; i++) {}
    vm.message = 'C';
  }, 0);  
}

Upvotes: 1

Views: 211

Answers (1)

Botje
Botje

Reputation: 30860

setTimeout works for me: https://codepen.io/anon/pen/VrZqRa?editors=1010

Also, never do huge for loops like that in JavaScript: they will completely freeze your event loop (which needs to handle both javascript and user interactions).

Upvotes: 1

Related Questions