vue js DOM management

·

2 min read

When we worked on any type of web development we need to handle DOM management most of the time. In vue we can manage DOM by using following ways ?

Access any input reference

<input type="text" name="firstname" id="firstname" ref="firstname"/>

Here we have added ref attribute with an input. now in script we need to use following code for input management dynamically using java script:

Focus in input

this.$refs.firstname.focus();

Assign value in input

this.$refs.firstname.value = 'ashish';

Access any div/paragraph reference

<div class="block">
<p>first para</p>
<p>second para</p>
</div>

Here we have added the same ref attribute with the div. Now what we need to do in our script:

change div background color

this.$refs.block.style.backgroundColor = 'yellow';

Access all the p tags available in that particular div

this.$refs.block.querySelectorAll('p');

change style/access html of all the p tags available in that particular div

const paras = this.$refs.block.querySelectorAll('p');

  if (paras.length > 0) {
    paras.forEach((e:any, index: number) => {
      e.innerText = `${e.innerText} ${index}`;
      e.style.color = 'green';
    });
  }

These are the ways we can handle DOM in vue application: