Reputation: 319
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?
Upvotes: 2
Views: 2336
Reputation: 55644
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
.
Upvotes: 2