Home » vue » VueJS detect when DOM is ready after using push() to add a new element

VueJS detect when DOM is ready after using push() to add a new element

Posted by: admin November 26, 2021 Leave a comment

Questions:

In vueJS I have a <table>. if I click on a button a new row will get inserted in the table using

this.rows.push({
        title: '',
        price: ''
      });

The problem is that I am using this function:

$(".price").numeric({
        decimal: false,
        negative: false
      });

This is a jquery function that force inputs to only be integer.
So when a new row is added which has a input the above function no longer works.

If I add a new row and run

$(".u-price").numeric({
        decimal: false,
        negative: false
      });

It will make the new row only accept integers

I have also tried to do it all in once like this:

addRow() {
      this.rows.push({
        title: '',
        price: '',
      });
      $(".price").numeric({
        decimal: false,
        negative: false
      });
    },

To toggle the numeric helper right after but it doesnt work.
So how can I detect when a new row is added so I can run the numeric helper after?

Answers:

I’d use a directive for this, as is.

Vue.directive('numeric', {
  inserted(el) {
    $(el).numeric({
      decimal: false,
      negative: false
    })
  }
})

In the template:

<input v-numeric type="text" />

Working pen.

###

You can use Vue.nextTick(). https://vuejs.org/v2/guide/reactivity.html#Async-Update-Queue

In order to wait until Vue.js has finished updating the DOM after a
data change, you can use Vue.nextTick(callback) immediately after the
data is changed. The callback will be called after the DOM has been
updated