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,而不是具体的事件。

阅读 3k
2 个回答

题主的需求比较特殊,如果是这样的话可能只能使用render代替template了:

<div id="app">
  <button-counter :event="'click'">abc</button-counter>
</div>
const counter = Vue.component('button-counter', {
  render(createElement) {
    return createElement(
      'button', {
        on: {
          [this.event]: this.increment,
        },
      },
      `${this.counter}`,
    )
  },
  data() {
    return {
      counter: 0,
    }
  },
  props: {
    event: String
  },
  methods: {
    increment() {
      this.counter += 1
    },
  },
})

new Vue({
  el: '#app',
  components: {
    'button-counter': counter,
  },
})

父组件传参给字组件都是通过props的,props可以是function,所以你可以传一个function给字组件

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题