Как правильно использовать Vue mixins - PullRequest
0 голосов
/ 14 октября 2019

Я работаю с 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"

Как я могу решить эту ошибку / проблему? Когда потребуется дополнительная информация, просто дайте мне знать, и я обновлю свой пост.

1 Ответ

0 голосов
/ 15 октября 2019

Просто для людей, которые хотят добиться того же, пример, как я это сделал. Я использовал этот способ в приложении Laravel 6, поэтому я не уверен, работает ли он в других проектах / фреймворках или автономно.

Мой помощник API:

let apiHelper = {
  getRequest(url, callback) {
    console.log ("you hit the apiHelper getRequest function")
    let baseUrl = `http://${subDomain}.festipay.xlan/api/v1`;
    let header = {headers: {'Content-Type': 'application/json'}}


    axios.get(baseUrl + url, header)
      .then(function (response) {
        callback(response.data.data);
      })
      .catch(function (error) {
        // do something with the error...
      });
  },
}
export default apiHelper;

(раздетая) копия моего хранилища vuex:

import Vue from 'vue';
import Vuex from 'vuex';
import apiHelper from '../apiHelper';   // import the helper class here

Vue.use(Vuex);

const appSettingStore = new Vuex.Store({
    state: {
        accounts: [],
    },
    mutations: {
        setAccounts(state, accounts) {
            state.accounts = accounts;
        }
    },
    actions: {
        getAccounts({commit}) {
            apiHelper.getRequest("/app_settings", (data) => {commit('setAccounts', data)});      // just call the method like this, note that you need to use a callback function to receive the result!
          });
        },
    }
});

export default appSettingStore;

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...