Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Mixin global method from Vuex

I have a mixin like this with a request method to call axios and handle errors, etc.:

import Vue from 'vue'
import axios from 'axios';
    
Vue.mixin({
    methods: {
        request(url, datas) {

        //Call axios and return premise
        [...]
    }
});

I have a store like this :

const actions = {
    selectEmployees: (store, keywords) => {
        this.request(`/users/list/search{/keywords}`).then(e => {
            store.commit('SELECT_EMPLOYEES', e.data)
        });
    }
}
    
let store = new Vuex.Store({
    state: state,
    mutations: mutations,
    getters: getters,
    actions: actions
})

I would like to use request to call axios but I have this error:

Error in mounted hook: "TypeError: Cannot read property 'request' of undefined" TypeError: Cannot read property 'request' of undefined

like image 742
alxb Avatar asked Oct 02 '18 20:10

alxb


People also ask

How to call a global function from a Vue mixin?

We will create a globalHelper function inside a Mixin and call it from a component. Open your main file then create a global mix: Now all of the above Mixin options will be automatically implemented for all components. For example, we can call the function from the component template: Plugins can also add global functions to Vue.

What is a mixin in Vue?

Basics. Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

How to create a global function in Vue without importing?

Let’s find out how to create a global function that can be called from anywhere without making any imports. A Mixin is an object that contains the same options as a component and can be reused and distributed between Vue components. We will create a globalHelper function inside a Mixin and call it from a component.

How to call a mixin from a component?

A Mixin is an object that contains the same options as a component and can be reused and distributed between Vue components. We will create a globalHelper function inside a Mixin and call it from a component. Open your main file then create a global mix:


1 Answers

Mixins, as stated from the docs, are used for components. Vuex is not a component itself. As I can see you're using the new import/export ways of working, just make your mixing a simple functions that are exported. Then elsewhere either attach them to Vue as mixin, or use it externally in the store. Something along the lines (semi code):

// mixin.js
export default function request() {}

// main.js
Vue.mixin({
    methods: {
        request: mixin.request // will provide this.request in each component
    }
}

// store.js
mixin.request() // will fire the method
like image 90
Andrey Popov Avatar answered Oct 12 '22 13:10

Andrey Popov