[Vuejs]-Trigger a Vue components method by property

0👍

Yes, this is definitely possible.

The easiest way would be to pass a plain string, eg

<navigation button-left="goback" />

Note there’s no v-bind.

Then in your component, you can use the prop value. Something like…

export default {
  template: `<button @click="runButtonLeft">Go</button>`,
  props: ['buttonLeft'],
  methods: {
    runButtonLeft () {
      if (typeof this[this.buttonLeft] === 'function') {
        this[this.buttonLeft]()
      } else {
        console.error('Invalid method name:', this.buttonLeft)
      }
    },
    goback () {
      console.log('Run this.')
    }
  }
}

You didn’t specify what should be used to trigger the method execution so I’ve gone with a click event.

Leave a comment