vue如何根据配置监听的事件类型?

Vue.component('button-counter', {

  template: '<button v-on:click="increment()">{{ counter }}</button>',

  data: function () {

    return {

      counter: 0

    }

  },

  methods: {

    increment: function () {

      this.counter += 1

    }

  },

})

比如上面的组件,我希望 v-on监听的事件是 父组件传递过来的,而不是在这里写死为click,我该怎么写?

我当然知道使用props传递,我想知道v-on后面该怎么写。如果直接写propname的话vue会认为要监听的事件是propname,而不是具体的事件。


白猪掌柜的
浏览 468回答 1
1回答

RISEBY

题主的需求比较特殊,如果是这样的话可能只能使用render代替template了:<div id="app">&nbsp; <button-counter :event="'click'">abc</button-counter></div>const counter = Vue.component('button-counter', {&nbsp; render(createElement) {&nbsp; &nbsp; return createElement(&nbsp; &nbsp; &nbsp; 'button', {&nbsp; &nbsp; &nbsp; &nbsp; on: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [this.event]: this.increment,&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; `${this.counter}`,&nbsp; &nbsp; )&nbsp; },&nbsp; data() {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; counter: 0,&nbsp; &nbsp; }&nbsp; },&nbsp; props: {&nbsp; &nbsp; event: String&nbsp; },&nbsp; methods: {&nbsp; &nbsp; increment() {&nbsp; &nbsp; &nbsp; this.counter += 1&nbsp; &nbsp; },&nbsp; },})new Vue({&nbsp; el: '#app',&nbsp; components: {&nbsp; &nbsp; 'button-counter': counter,&nbsp; },})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript