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>
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With