[英]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(){});
我可以在 jquery 中使用$(document).on('click', '.newButton', function(){});
方法解决这个问题。 how can I solve the same thing at VUE我如何在 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>
In vue.js, you normally don't manipulate DOM in javascript;在 vue.js 中,您通常不会在 javascript 中操作 DOM; If you want to conditionally show a component, you can use v-if
or v-show
directives ;如果你想有条件地显示一个组件,你可以使用v-if
或v-show
指令; And also you should define your functions as methods
instead of data
:而且你应该将你的函数定义为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>
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.