Step-by-Step Guide on Monitoring alterations within a division in Vue 3

Is there a way to monitor changes such as class modifications or text updates within a div using Vue 3?

from:

<p class="font-bold">My text</p>

to:

<p class="font-bold color-red">My updated text.</p>

I attempted to use the watch method in Vue 3 but it does not track changes within a div.

watch(myDiv, (newValue, oldValue) => {
// This code is not effective for monitoring changes within myDiv.
})

Answer №1

When creating a SFC component, you can include your paragraph text and use a hook like onUpdated to catch every change.

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

For example, you can see how it works here: https://stackblitz.com/edit/vue-5qtyjg

Answer №2

Before you can watch certain properties, you must first bind them, such as

<p :class="classes">{{ text }}</p>
. Additionally, you have the option of using a 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 class="mydiv" :class="classes">{{ text }}</p>
  <input v-model="text" />
  <button @click="addClass">class</button>
</div>

Answer №3

With Vue3, utilizing refs in templates is now possible. For more information, refer to the documentation.

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

It is now feasible to define them in the template. The DOM element will be stored in myDiv.value

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am unable to display my JSON data in Next.js using a fetch request

I'm having trouble understanding the code, and it seems like the API is open to anyone since it's just a simple JSON. However, I keep getting an error: Error Message: Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit th ...

Prevent users from navigating back in their browser with jQuery

As I work on developing an online testing app, one of the requirements is to prevent users from refreshing the page or going back during the test until it has ended. While I have successfully disabled the refresh action in jQuery using various methods with ...

Starting http-server in the background using an npm script

Is there a way to run http-server in the background using an npm script, allowing another npm script, like a Mocha test with jsdom, to make HTTP requests to http-server? To install the http-server package, use: npm install http-server --save-dev In your ...

Having difficulty viewing the images clearly

My JavaScript codes for scrolling images are not displaying all the images when viewed on Google Chrome. Is there a solution available? Below is the included JS code and CSS. data=[ [" images/img1.jpg"," Image1","pic01.jpg"], [" images/img2.jpg","Image2 " ...

Encountering an issue with Angular directive attributes

I am attempting to create an angular directive that will extract a substring from a passed-in attribute. Below is the code I have written: HTML: <body ng-controller="MainCtrl"> <div><substring message="This is a test."></substri ...

Dealing with the error "Type 'date[]' is not assignable to type '[date?, date?]' in a React hook

I'm attempting to assign a date range but encountering an error that states: Type 'Date[]' is not assignable to type '[Date?, Date?]'. Types of property 'length' are incompatible. Type 'number' is not assignab ...

A method that sorts an array of objects based on their properties

I am currently working with two specific objects: clinics: [ { id: 1, name: 'New Hampshire Veterinarian Clinic', plans: [ 'handle123', 'handle567', ] }, { ...

Having difficulty adding multiple items to the state array

I am currently working on a parent component that iterates over an array and passes props to a child component. In the child component (shown below), I have checkboxes with Font Awesome icons for users to mark their selections. When a user checks a box, I ...

Overriding filters in AngularJS and injecting dependencies into modules

My application relies on two filter modules: var app = angular.module('MyApp',['Filter1','Filter2']); Both modules contain filters with the same name: var filterapp1 = angular.module('Filter1',[]); filterapp1.f ...

Upgrade jQuery visibility and opacity animations to pure JavaScript for a more lightweight solution

Currently I am in the process of removing jQuery from an older website. However, I have encountered a problem with an animation that is currently being used. I have managed to replicate the opacity fade effect, but I am struggling to smoothly transition t ...

Is it possible to import multiple versions of a JavaScript file using HTML and JavaScript?

After extensive research, I am starting to think that using multiple versions of the same JavaScript library on a single page is not possible (without utilizing jquery Can I use multiple versions of jQuery on the same page?, which I am not). However, I wan ...

p5.js experiencing issue: Uncaught TypeError - Unable to access property 'transpose3x3' due to null value

I have a simple website built with Flask where I am running several p5.js sketch animations, and everything is working smoothly. However, when I try to add a new sketch that utilizes WEBGL, I encounter the following error: Uncaught TypeError: Cannot read p ...

Why does the request for server parameter 'occupation=01%02' function correctly, while 'occupation=01%2C02' or 'occupation=01&occupation=02' result in an error?

There seems to be an issue with the parameter when using the API to request data from the server. The value 'occupation=01%02' works correctly when entered directly into the browser URL, but errors occur when using 'occupation=01%2C02' ...

Building an API using .Net Core paired with a captivating VUE spa

I am currently working on hosting a Vue SPA client within the wwwroot folder of my API. I have successfully set up build scripts to compile and place the SPA into the folder. Additionally, I am utilizing app.UseSpa() to handle requests during development. ...

Creating and dynamically updating identical state using a single method in React

Is there a way to create a single method named handleChange that can handle checkbox changes and update their respective states appropriately? I attempted to dynamically call a function based on the checkbox name, but it's not working as expected. Can ...

Increase the space below the footer on the Facebook page to allow for an

I recently created a webpage at and noticed that it is adding extra height below the footer on my Facebook page: "" I am seeking assistance on how to remove this additional 21px height below all content in the footer. I have tried various templates but n ...

Tips for finding the correct file path for a .js file when utilizing the require function

I am currently working on an ExpressJS project and I am facing an issue with using a .js module inside another. Despite using require to retrieve the .js module, it appears that the path is incorrect which is preventing me from locating the module. How can ...

Is there a way to assign a null value to an empty material UI text field when submitting the form, rather than an empty string?

One issue I am facing is that the default value of the text field is zero, but when I submit the form, the value of the text field becomes an empty string instead. This is not the intended behavior as I want the value to remain zero in the end. How can I r ...

Navigating through an array in Pug

I'm currently extracting data from an external API in JSON format and sending it to my view. The main issue I'm facing is that one of the properties within the Object consists of an Array of Objects. Using the Pug Documentation for iteration, I&a ...

Ways to display multiple select options based on the user's selection of multiple choices and ensure they remain hidden and reset when deselected with the use of

There is a select options field that contains languages, where the user can choose multiple language options or just one. When the user selects a language, a new select option should appear for them to choose their proficiency level in that language. If t ...