V
V
vetsmen2018-02-01 02:37:19
Vue.js
vetsmen, 2018-02-01 02:37:19

How to catch markup load event in Vue.js?

I have several blocks

<div v-if="stage == 0">
...
</div>
<div v-else-if="stage == 1">
<div class="elem"></div>
...
</div>

// при каком-то событии делаю:
this.stage = 1;
let elem = document.querySelector('.elem');

The problem is that in this case, I get null instead of elem, because the element is not yet in the DOM tree. If I initialize it after 100ms (using setTimeout) then everything works fine.
I understand that setTimeout is a terrible crutch, I would like to catch some tree loading event built into Vue.js. How can I do that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-01
@vetsmen

There is such a thing - nextTick . With it, you can call a function after updating the DOM tree. That is, do this:

this.stage = 1;
this.$nextTick(() => {
  const elem = document.querySelector('.elem');
  ...
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question