Я работаю с VueJS (как часть Laravel) уже несколько дней и хочу повторно использовать код, например, для выполнения вызовов API. Я обнаружил в Google, что "Mixins" - это путь, так как нельзя использовать нативные классы ES6. Я знаком с javascript mixin's, но не могу заставить его работать по Vue.
Я нашел несколько реализаций в Google и попробовал их, но я не могу заставить его работать. Может я что то не так понимаю?
app.js
...
import appSettingStore from "./stores/appSettingStore";
...
export const eventBus = new Vue();
const app = new Vue({
el: '#app',
appSettingStore,
// apiHelper,
// data() {
// return {
// data: {
// testData: "",
// store: appSettingStore,
// }
// }
// },
});
...
appSettingStore.js
import Vue from 'vue';
import Vuex from 'vuex';
import apiHelper from '../apiHelper'; // tried with and without this line
Vue.use(Vuex);
...
const appSettingStore = new Vuex.Store({
mixins: [apiHelper],
state: {
accounts: [],
},
mutations: {
setAccounts(state, accounts) {
// some mutation logic
}
},
actions: {
getAccounts({commit}) {
// Here i want to call the mixin method, tried something like:
// this.getRequest(x,y,z);
// apiHelper.getRequest(x,y,z);
// getRequest(x,y,z);
}
}
});
export default appSettingStore;
apiHelper.js
const apiHelper = Vue.mixin({
methods: {
getRequest(url, headers, body) {
let subDomain = window.location.host.split('.')[0];
let baseUrl = `http://${subDomain}.festipay.xlan/api/v1`;
let header = {headers: {'Content-Type': 'application/json'}}
axios.get(baseUrl + "url", header)
.then(function (response) {
return response.data.data;
})
.catch(function (error) {
return error;
});
}
}
});
export default apiHelper;
Действие getAccounts
называется "называетсяmsgstr "из другого компонента vue (протестировано с console.log ()).
Ошибка, которую я имею в консоли devtools: Error in mounted hook: "TypeError: this.getRequest is not a function"
Как я могу решить эту ошибку / проблему? Когда потребуется дополнительная информация, просто дайте мне знать, и я обновлю свой пост.