Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a Global Mixin method from a Vue instance

Let's suppose that I have the following situation, using a Global Mixin to create a global helper method with Vue:

import Vue from "vue";

Vue.mixin({
    methods: {
        replaceString: function (word) {
            return word.toLowerCase().replace(/\W/g, '');
        }
    }
});

let vm = new Vue({
    methods: {
        doSomething: function() {
             console.log(this.replaceString('Hello World'); //helloword
        }
    }
});

I know that I can invoke the method inside the other methods, inside of the component and their childs. But how can I invoke the mixin method "replaceString" from the Vue instance "vm"? I tried to use "vm.replaceString", but keeps returning "undefined".

like image 936
Marcelo Rodovalho Avatar asked Sep 05 '25 03:09

Marcelo Rodovalho


1 Answers

Few changes to your code and it works:

  1. You should change the definition of your mixin (var mixin instead of Vue.mixin)
  2. Import the mixin to your new vue component (mixins = [mixin])

    import Vue from "vue";
    
    var mixin = {
        methods: {
            replaceString: function (word) {
                return word.toLowerCase().replace(/\W/g, '');
            }
        }
    };
    
    let vm = new Vue({
        mixins: [mixin]
        methods: {
            doSomething: function() {
                console.log(this.replaceString('Hello World'); //helloword
            }
        }
    });
    
like image 115
Doron Avatar answered Sep 08 '25 22:09

Doron