Home > Back-end >  How to Watch changes inside a div in Vue 3
How to Watch changes inside a div in Vue 3

Time:10-14

How can I Watch for any changes like classes or text change inside a div in Vue 3.

from

<p >My text</p>

to:

<p >My updated text.</p>

I have tried the Vue 3 Watch method but the Watch method is not looking for changes inside a div.

watch(myDiv, (newValue, oldValue) => {
// not working for changes inside a myDiv. 
})

CodePudding user response:

To watch some properties you need to bind it first, like <p :>{{ text }}</p>, also, you can use mutationObserver:

const {ref, onMounted, onBeforeUnmount} = Vue
const app = Vue.createApp({
  data() {
    return {
      text: 'My text',
      classes: 'font-bold'
    };
  },
  watch: {
    text(newValue, oldValue)  {
      console.log(newValue)
    },
    classes(newValue, oldValue)  {
      console.log(newValue)
    }
  },
  methods: {
    addClass() {
      this.classes = 'font-bold color-red'
    }
  },
  setup() {
    let observer = null
    let target = ref(null)
    let options = {subtree: true, childList: true, attributes: true}
    const callback = (mutationList, observer) => {
      for (const mutation of mutationList) {
        if (mutation.type === 'childList') {
          console.log('A child node has been added or removed.');
        } else if (mutation.type === 'attributes') {
          console.log(`The ${mutation.attributeName} attribute was modified.`);
        }
      }
    };
    onMounted(() => {
      target = document.querySelector(".mydiv")
      observer = new MutationObserver(callback);
      observer.observe(target, options);
    });
    onBeforeUnmount(() => observer.disconnect())
  },
})
app.mount('#demo')
.color-red {
  color: red;
}
.font-bold {
  font-weight: 700;
}
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <p  :>{{ text }}</p>
  <input v-model="text" />
  <button @click="addClass">class</button>
</div>

CodePudding user response:

In Vue3 you can use refs in template. Docs

<p ref="myDiv" >{{text}}</p>

Now you can define them in template. myDiv.value will hold DOM element

const myDiv = ref(null)
const text= computed(() => {
  if(myDiv.value.classList ... rest of your logic for checking classes)
  return "Text"
  else return "Updated Text"
})

CodePudding user response:

you can create a SFC component with your paragraph and catch every change with a hook onUpdated

onUpdated(() => {
  console.log('updated');
});

example: https://stackblitz.com/edit/vue-5qtyjg

  • Related