S
S
Sharov Dmitry2017-04-27 11:37:34
JavaScript
Sharov Dmitry, 2017-04-27 11:37:34

How to set global methods in Vue?

Tell me how to set global methods in vue.js
So that I could then use them in any module
Both for displaying information And in module methods
<p>{{ globalMetodName(param1, param2) }}<p>

modeleMetod: function(){
    this.globalMetodName(param1, param2);
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Kulakov, 2017-04-27
@vlom88

You can also use the mixin mechanism: https://ru.vuejs.org/v2/guide/mixins.html
Create a mixin object:

// определяем объект примеси
var myMixin = {
  created: function () {
    this.hello()
  },
  methods: {
    hello: function () {
      console.log('привет из примеси!')
    }
  }
}

And then it can be injected into any component or globally:
Vue.mixin(myMixin)

W
wostex, 2017-04-27
@wostex

Make a plugin. Example: https://jsfiddle.net/wostex/63t082p2/45/

<div id="app">
  <p>{{ helloText }}</p>
</div>

const mylib = {
    hello : (text1, text2) => { 
    	return `Hello! ${text1} ${text2}`
    },
    install: function(Vue){
      Object.defineProperty(Vue.prototype, 'mylib', {
        get () { return mylib }
      })
    }
};

Vue.use(mylib);

new Vue({
    el: '#app',
    data: {
    	helloText: mylib.hello('one', 'two')
    }
});

You can call methods on any component like `this.mylib.hello(...)`

A
Anton Boltnev, 2019-12-12
@AntonBoltnev

What's wrong with mapActions (at the bottom of the page) and mapGetters (at the bottom of the page) ? Unless, of course, you are using Vuex in the project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question