2

I wrote a Vue.js plugin to access Vue functions globally:

const MyPlugin = {
  install (Vue, options) {
    Vue.myFunction = function () {     
      console.log('Test')
    }
  }
}
export default { MyPlugin }

And include it in main.js file:

import MyPlugin from './plugins/my-plugin.js'
Vue.use(MyPlugin)

but, when I try to invoke myFunction from a Vue component like that:

<a href="#">
  <i class="fa fa-gears fa-fw"></i>  {{ myFunction() }} <span class="fa arrow"></span>
</a>

it gives me the error below:

Property or method "myFunction" 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

What I need to do to access "myFunction" in vue components?

0

1 Answer 1

2

If you're trying to access a global method from the template, it would need to be available on the Vue component's instance. So you'd need to set the myFunction function on the Vue.prototype object:

install (Vue, options) {
  Vue.prototype.myFunction = function () {     
    console.log('Test')
  }
}

See the docs on writing plugins.


And as you can see in the docs, it's a common convention to prepend $ to these types of global functions in order to more easily distinguish them from other methods on the Vue instance. So in your case, it would be good to set the function to Vue.prototype.$myFunction.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.