我有以下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);
}
});
当我单击自定义按钮时,没有任何反应。我认为是因为它在onSubmit
组件中寻找ti-button
,但是如何在ti-page-inquire
组件中寻找它?
答案 0 :(得分:3)
答案 1 :(得分:1)
这可能是因为您需要听native click event。因此,您需要使用.native
修饰符..
<ti-button v-bind:button="page.button" v-on:click.native="onSubmit"></ti-button>
仅当按钮是ti-button
组件的根元素时,此选项才有效。否则,您必须将事件监听器传递给ti-button
组件中的按钮,就像这样..
<button v-on="$listeners" ...> ... </button>
答案 2 :(得分:0)
尝试使用ti-button
函数从this.$emit
组件向父组件发出事件:
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
可以是任何类型