[Vuejs]-Why does Javascript not see new elements created by VueJS?

0👍

jQuery binds its the click handler to the li elements that exist at the time the jQuery code runs. When Vue later adds new li elements, they don’t have that click handler attached, because Vue doesn’t know you attached them using non-Vue code. (Other updates Vue may make to the DOM that require re-building the list can destroy the jQuery binding on even the elements that originally had them, for the same reason.)

You could resolve this by using a delegated event from a parent element that exists when the jQuery runs, and which Vue will not modify later:

$('#app').on("click", "li", function() {...})

…but a much better solution would be to avoid trying to mix jQuery and Vue code in the first place, so you won’t run into these problems caused by them fighting against each other over control of the DOM.

Put these handlers in Vue instead, and the framework will include them whenever it needs to update the DOM:

var app = new Vue({
  el: '#app',
  data: function() {
    return {
      array: [1, 2, 3, 4]
    };
  },
  methods: {
    update() { // <-- changed to ES6 arrow function shorthand, to preserve `this`
      this.array = [1, 2, 3, 4, 5, 6, 7, 8]; // `this` refers to the current component; you often won't have an external variable name like `app` to refer to here
    },
    handleClick(item) {
      console.log(item) // You probably want the data, not the DOM element (but if necessary the element would be the `event.target`)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app">
  <ul>
    <li v-for="item in array" v-on:click="handleClick(item)">{{item}}</li>
  </ul>
  <button type="button" name="button" v-on:click="update">Update Array</button>
</div>

Leave a comment