Reputation: 3
I am pretty new to Vue.js.
I have a requirement wherein I want to bind events to the generic button template.
I tried using the below method.
Vue.component('ac-btn', {
props: [
'clickevent'
],
methods: {
greet: function () {
alert("I am Called");
}
},
template: '<button type="button" :click="clickevent" class="btn btn-secondary btn-sm"><slot>button</slot></button>'
});
But the click even is not called. Any idea of how to bind the click event to generic button template dynamically?
Edit:
@Saurabh
I tried your suggestion above and below is how it looks in my project.
Vue.component('ac-parent', {
methods: {
greet: function () {
alert("Hiey");
}
},
template: `<div class="container-fluid">
<div class="row">
<div class="col-lg-3 col-md-4">
<div>
<ac-child :onClick="greet">Custom value to replace generic slot value</ac-child>
</div>
</div>
</div>`
});
Vue.component('ac-child', {
template: '<button type="button" @click="clickevent" class="btn btn-secondary btn-sm"><slot>button</slot></button>'
});
Still this doesn't work. Am I doing something wrong?
Upvotes: 0
Views: 1395
Reputation: 1092
It's not good idea to pass callback through component prop :onClick="greet"
... Better way is to emit event from child to parent component this.$emit('click', event)
, so you can catch this event in parent component and do something... After this you can use this button component like native button with <ac-child @click="greet">Custom Button</ac-child>
Upvotes: 1
Reputation: 753
Please try using below code:
app.js
Vue.component('ac-parent', {
methods: {
greet: function () {
alert("Hiey");
}
},
template: `<div class="container-fluid">
<div class="row">
<div class="col-lg-3 col-md-4">
<div>
<ac-child :onClick="greet">Custom value to replace generic slot value</ac-child>
</div>
</div>
</div>
</div>`
});
Vue.component('ac-child', {
props: ['onClick'],
template: '<button type="button" @click="onClick" class="btn btn-secondary btn-sm"><slot>button</slot></button>'
});
new Vue({
el: '#vue-app'
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Title</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="vue-app">
<ac-parent></ac-parent>
</div>
</body>
<script src="./app.js"></script>
</html>
Do let me know in case you still face any issues
Upvotes: 0