Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In vuejs, why I need to use nextTick while use mounted hooks?

Tags:

vue.js

As the docs said, I need to use nextTick to confirm $el ready, but in another page, it roughly means that the $el has been ready while mounted called. So, why need to use nextTick while use mounted hooks?

like image 261
quietcoder Avatar asked Nov 08 '25 04:11

quietcoder


1 Answers

I believe el is indeed mounted when mounted hook is called. Real usage for nextTick is described here. It's mainly used when you need a direct DOM access (which is not recommended btw) immediately after changing something affecting your DOM in your code. Check this code:

new Vue({
  el: '#app',
  data: {
    text: 'one'
  },
  components: {
    'child' : {
      template: `<p>{{ text }}</p>`,
      props: ['text']
    }
  },
  mounted: function() {
    console.log(document.querySelector('p').textContent); // 'one'
    this.text = 'two'; // assign new value
    console.log('after text has changed: ');
    console.log(document.querySelector('p').textContent); // still 'one'
    this.$nextTick(function() {
      console.log('nextTick: ', document.querySelector('p').textContent); // now 'two' after 'nextTick'
    })
  }
});
<script src="https://unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <child :text="text"></child>
</div>

So, I guess migration docs are misleading in this case.

like image 102
Egor Stambakio Avatar answered Nov 10 '25 17:11

Egor Stambakio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!