[英]onclick event not firing in vue.js
我有以下Vue.js
模板:
<script type="text/x-template" id="ti-page-inquire">
<div>
<h3 class="mdc-typography--headline3">{{page.name}}</h3>
<ti-button v-bind:button="page.button" v-on:click="onSubmit"></ti-button>
</div>
</script>
<script type="text/x-template" id="ti-button">
<button class="mdc-button mdc-button--raised" v-bind:title="button.name">{{button.name}}</button>
</script>
脚本
Vue.component('ti-page-inquire', {
props: ['page'],
template: '#ti-page-inquire',
methods : {
onSubmit : function() {
alert(1);
}
}
});
Vue.component('ti-button', {
props: ['button'],
template: '#ti-button',
mounted: function () {
// ripple on button
mdc.ripple.MDCRipple.attachTo(this.$el);
}
});
当我点击我的自定义按钮时,什么也没有发生。 我认为这是因为它在ti-button
组件中查找onSubmit
,但是我如何让它在ti-page-inquire
组件中查找?
组件是黑盒子,您应该捕获其中的所有事件并将它们发送到外部世界。
Vue.component('ti-button', {
props: ['button'],
template: '#ti-button',
mounted: function () {
// ripple on button
mdc.ripple.MDCRipple.attachTo(this.$el);
},
methods: {
buttonClicked: function() {
this.$emit('button-clicked');
}
}
});
<script type="text/x-template" id="ti-page-inquire">
<div>
<h3 class="mdc-typography--headline3">{{page.name}}</h3>
<ti-button v-bind:button="page.button" v-on:button-clicked="onSubmit"></ti-button>
</div>
</script>
<script type="text/x-template" id="ti-button">
<button class="mdc-button mdc-button--raised" v-bind:title="button.name" @clicked="buttonClicked">{{button.name}}</button>
</script>
这可能是因为您需要监听原生点击事件。 所以你需要使用.native
修饰符 ..
<ti-button v-bind:button="page.button" v-on:click.native="onSubmit"></ti-button>
这仅在按钮是ti-button
组件的根元素时才有效。 否则,您必须像这样将事件侦听器传递给ti-button
组件中的按钮。
<button v-on="$listeners" ...> ... </button>
尝试使用this.$emit
函数从ti-button
组件向父组件发出事件:
Vue.component('ti-button', {
props: ['name'],
template: '#vButton',
data: {
name: 'hi'
},
methods: {
submit() {
this.$emit('submit')
}
}
});
<template id="vButton">
<button v-bind:title="name" @click="submit">{{name}}</button>
</template>
发出的事件submit
它在父组件中调用,如v-on:submit="onSubmit"
并使用onSubmit
方法处理:
<script type="text/x-template" id="ti-page-inquire">
<div>
<h3 class="mdc-typography--headline3">{{page.name}}</h3>
<ti-button v-bind:button="page.button" v-on:submit="onSubmit"></ti-button>
</div>
</script>
Vue.component('ti-page-inquire', {
props: ['page'],
template: '#ti-page-inquire',
methods : {
onSubmit : function() {
alert(1);
}
}
});
有时你还需要发出一些参数,所以你可以这样做:
this.$emit('submit',params)
params
可以是任何类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.