Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

watch changes in html element using vue

Tags:

vue.js

I'm trying to watch HTML element in the followiing way:

 computed: {
    content(){
      return document.querySelector(".tab-content")
    }
 },
 watch: {
    content(newVal) {
      return newVal;
    }
 }

but when .tab-content changes (it's innerHTML) , vue wont track/respond to that. any idea why?

like image 531
yariv bar Avatar asked Oct 27 '25 15:10

yariv bar


1 Answers

You can use MutationObserver.

It's a vanilla JS feature that lets you watch DOM element and react to the changes(aka mutations)

https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

https://developer.mozilla.org/en-US/docs/Web/API/MutationRecord

<script setup>

let observer = null;
let target = document.querySelector(".tab-content");
let options = {
    subtree: true
    //childList: true,
    //attributes: true,
}

onMounted(() => {
  observer = new MutationObserver((mutationList, observer) => {

    //Analyse mutationList here for conditional processing
  });

  observer.observe(target, options);
});

onUnmounted(() => observer && observer.disconnect());

</script>
<template>
    <div class="tab-content"></div>
</template>
like image 123
Alpesh Patil Avatar answered Oct 30 '25 13:10

Alpesh Patil



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!