javascript - How does vue configure the event types it listens to?
仅有的幸福
仅有的幸福 2017-06-12 09:32:45
0
2
649
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.

仅有的幸福
仅有的幸福

reply all(2)
洪涛

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,
  },
})
黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template