在append()元素之后的VueJS中,click方法无效

时间:2018-11-06 04:22:16

标签: javascript vue.js

我可以使用public ICollection<Book> Books { get; set; } 方法在jquery中解决此问题,如何在VUE中解决同一问题

$(document).on('click', '.newButton', function(){});
new Vue ({
  el: '#app',
  data: {
    oldButton: function () {
      $('#app').append('<button v-on:click="newButton">The New Button</button>');
    },
    
    newButton: function () {
      console.log('Hello World!');
    },
  },
});

2 个答案:

答案 0 :(得分:4)

在vue.js中,通常不会在javascript中操作DOM;如果要有条件地显示组件,可以使用v-if or v-show directives;另外,您还应该将函数定义为methods而不是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>

答案 1 :(得分:2)

如果您想拥有一系列按钮:

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)
   }
  }

})

并且:

<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>