Vue directive with classList.add doesn't immediately update the DOM element

144 Views Asked by At

Adding a custom class name to an element via the directive takes tons of time. The element is rendered, then after a few seconds, the class gets added. The effect is not immediate, which is extremely weird.

Both bind and update have the same function. The directive is called via v-my-directive={active: false}, where active is a boolean that changes after 3-4 seconds

The function's content:

bind(el, payload) {
    const value = payload ? payload.value : null;
    if(!value) return;
    const active = value.active;
    process(el, active);
}

The function process is straight forward

function process(el, active) {
   if(!el) return;
   if(active) el.classList.add("my-class");
   if(!active) el.classList.remove("my-class");
}

This directive is implemented in 5 components only.

Expected

  • The directive adds the content directly to the classes list.

Actual:

  • The directive gets called. It process the function and executes the insertion of the new class.
  • The DOM element doesn't get the new class until a few seconds later, and if I try to add multiple classes, there's a delay between them.

I've tried subtracting the Date.now(), its value is 0. There's no delay in the actual code, just a delay in insertion of the classes.

I've also tried className += "my-class", which is also as slow as the second one.

The slowness happens to the DOM element's update, not the actual code.

I appreciate any ideas / thoughts regarding this issue.

0

There are 0 best solutions below