[Vuejs]-Can you pass an external function to a Vue component as a prop?

0👍

You could define your methods like this in your component :

...
methods: {
   hi
}
...

But you will have to define it in every component where you need this function. Maybe you can use a mixin that define the methods you want to access from yours components, and use this mixins in these components ? https://v2.vuejs.org/v2/guide/mixins.html

Anoter solution ( depending on what you try to achieve ) is to add your method to the Vue prototype like explained here :
https://v2.vuejs.org/v2/cookbook/adding-instance-properties.html

Vue.prototype.$reverseText = function(string) {
  return string.split('')
    .reverse()
    .join('')
}

With this method defined in the Vue prototype, you can use the reverseText method like this in all of your components template :

...
<div> {{ $reverseText('hello') }} </div>
...

Or from yours script with this :

methods: {
  sayReverseHello() {
    this.$reverseText('hello')
  }
}

Leave a comment