search

Home  >  Q&A  >  body text

javascript - How does vue configure the event types it listens to?

Vue.component('button-counter', {
  template: '<button v-on:click="increment()">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
    }
  },
})

For example, in the above component, I hope that the event v-on listens to is passed by the parent component, instead of writing it as click here. How should I write it?

Of course I know how to use props to pass, I want to know how to write v-on later. If you write propname directly, Vue will think that the event to be monitored is propname, not the specific event.

仅有的幸福仅有的幸福2729 days ago599

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-06-12 09:34:45

    The questioner has special needs. If so, you may have to use render instead of template:

    <p id="app">
      <button-counter :event="'click'">abc</button-counter>
    </p>
    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,
      },
    })

    reply
    0
  • 黄舟

    黄舟2017-06-12 09:34:45

    Parent components pass parameters to subcomponents through props. Props can be functions, so you can pass a function to subcomponents

    reply
    0
  • Cancelreply