create a global role in Vue

Asked

Viewed 1,384 times

2

Good afternoon, I’m a beginner in both javascript and Vue, and I’m having a hard time creating a global role in Vue. Could someone give me an example? Thank you

  • 1

    Hello Elisangela, welcome to Stackoverflow in English. Can you show us what part of your code you’re struggling with? Make a tour as well.

  • 1

    Hi Elisangela. Can you explain better what you mean by global function? And can you give more details about how you are structuring your code? For example, do you use a module manager? Your code has require or import?

  • 1

    Good morning, I have an ajax request running on the Mounted hook, but this same request needs to be made when selecting an item from select (I’m using materialize for the components), because it is passed as parameter in my query. However I am not able to call this same function created on the Mounted hook in the select event.

1 answer

3


To add a global method to Vue you can create a plugin:

According to Vue.js - Plugins:

MeuPlugin.install = function (Vue, options) {
  // 1. Adiciona o método global ou propriedade
  Vue.meuMetodoGlobal = ...
  // 2. Adiciona uma diretiva global
  Vue.directive('minha-diretiva', {})
  // 3. Adiciona um método de instância
  Vue.prototype.$meuMetodo = ...
}

Then you add the plugin to Vue:

Vue.use(MeuPlugin)

In your code, to call the method.

Vue.meuMetodoGlobal(parametros);

Reference: Include global functions in Vue.js

  • Good morning, I am in doubt where to create the plugin. As I am using the router Vue, I should create a new file . Vue to my plugin and import it into main? thanks

  • For better organization yes

Browser other questions tagged

You are not signed in. Login or sign up in order to post.