我对Vue.js很新。
我有一个要求,其中我想将事件绑定到通用按钮模板。
我尝试使用以下方法。
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>'
});
但是没有调用点击。想知道如何动态地将click事件绑定到通用按钮模板吗?
编辑:
@Saurabh
我在上面和下面尝试了你的建议,看看它在我的项目中的表现。
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>'
});
这仍然不起作用。我做错了吗?
答案 0 :(得分:0)
请尝试使用以下代码:
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>
如果您仍然遇到任何问题,请告诉我
答案 1 :(得分:0)
通过组件prop :onClick="greet"
传递回调不是一个好主意...更好的方法是从子组件到父组件this.$emit('click', event)
发出事件,这样你就可以在父组件中捕获这个事件并做一些事情...在此之后,您可以使用此按钮组件,例如带有<ac-child @click="greet">Custom Button</ac-child>