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
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.
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.
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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With