Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between global methods and instance methods in Vue.js?

Tags:

vue.js

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?

like image 624
Shoto Azikuri Avatar asked Dec 24 '18 10:12

Shoto Azikuri


People also ask

What is instances in VUE JS?

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.

What is created () in Vuejs?

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.

What is type of Vue instance?

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.

What are methods in Vue?

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.


1 Answers

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.

like image 164
Roy J Avatar answered Sep 21 '22 05:09

Roy J