0
votes

Is it possible to trigger a Vue components method by handling the methods name to one of it's properties?

// main.vue
<navigation :button-left="goback()"></navigation>



// navigation.component.vue
...
props: ["buttonLeft"],
...
methods: {
  goback() {
    console.log('Run this.');
  },
},
...

I tried it like this but it gives me an error:

[Vue warn]: Property or method "goback" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

1
what's your use case?Boussadjra Brahim
The intention is to handle routing with the navigation. The buttons of the navigation differ from page to page. For some buttons it's necessary to handle a fixed routing path but for others it's just intended to go one step back in the routing history which should be done by a simple method.Mountain
What is meant to trigger the method execution?Phil
did you try to emit events from child component to the parent component and do what you want in the parent?Boussadjra Brahim

1 Answers

0
votes

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.