在vue.js中未触发onclick事件

时间:2018-10-17 17:47:45

标签: javascript vue.js vuejs2

我有以下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组件中寻找它?

3 个答案:

答案 0 :(得分:3)

组件是黑匣子,您应该捕获其中的所有事件并将它们发送到外部世界。

Fiddle example

totalTax.innerHTML = taxes;

答案 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可以是任何类型