Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In VueJS after append() an element the click method not works

I can solve this problem in jquery using the method $(document).on('click', '.newButton', function(){}); how can I solve the same thing at VUE

new Vue ({
  el: '#app',
  data: {
    oldButton: function () {
      $('#app').append('<button v-on:click="newButton">The New Button</button>');
    },
    
    newButton: function () {
      console.log('Hello World!');
    },
  },
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <button v-on:click="oldButton">The Old Button</button>
</div>
like image 468
Firmansyah Avatar asked Oct 25 '25 02:10

Firmansyah


2 Answers

In vue.js, you normally don't manipulate DOM in javascript; If you want to conditionally show a component, you can use v-if or v-show directives; And also you should define your functions as methods instead of data:

new Vue ({
  el: '#app',
  data: {
    showNewButton: false
  },
  methods: {
    oldButton: function () {
      this.showNewButton = true;
    },
    
    newButton: function () {
      console.log('Hello World!');
    },
  },
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
  <button v-on:click="oldButton">The Old Button</button>
  <button v-if="showNewButton" v-on:click="newButton">The New Button</button>
</div>
like image 81
Psidom Avatar answered Oct 27 '25 00:10

Psidom


If you want to have an array of buttons:

const app = new Vue({

  el: '#app',

  data: {
    btns: []
  },

  methods: {
    addBtn() {
      this.btns.push({
         name: 'Dynamic Button'
      })
    },
    showMsg(index) {
      console.log('Hello World!, from Button ' + index)
   }
  }

})

And:

<div id="app">    
  <ul>
     <li v-for="(btn, index) in btns">
        <button  @click="showMsg(index)" type="text"> {{ btn.name}}</button>             
     </li>
  </ul>    
<button @click="addBtn">Add Button</button>    
</div>
like image 22
Alireza Fattahi Avatar answered Oct 27 '25 01:10

Alireza Fattahi