Vue.js official docs about plugins describes global methods and properties and Vue instance methods.
// 1. add global method or property
Vue.myGlobalMethod = function () {
// some logic ...
}
// 4. add an instance method
Vue.prototype.$myMethod = function (methodOptions) {
// some logic ...
}
But it isn't clear which of this approach is better fit to define global functionality? Can someone explain difference or indicate some resource about different use cases of this two approaches?
The instances object is the main object for our Vue App. It helps us to use Vue components in our application. A Vue instance uses the MVVM(Model-View-View-Model) pattern. The Vue constructor accepts a single JavaScript object called an options object.
created() and mounted()in Vue.js If the Vue instance is created created () hook allows you to add code to be run. Let's look at the differences. Reactive data can be accessed when the processing of the options is finished and you can also change them if you want.
A Vue instance is essentially a ViewModel as defined in the MVVM pattern, hence the variable name vm you will see throughout the docs. When you instantiate a Vue instance, you need to pass in an options object which can contain options for data, template, element to mount on, methods, lifecycle callbacks and more.
A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events. Functions defined inside the methods object can be further called for performing actions.
An instance method will have an instance (this
) to be called from an operate on. A global-on-Vue function would have Vue
itself as its this
, which probably means you wouldn't want to use this
in it.
So: instance method if it should operate on an instance, global function if it is some sort of utility that doesn't operate on a Vue instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With