vuejs / vuex

🗃️ Centralized State Management for Vue.js.
https://vuex.vuejs.org
MIT License
28.42k stars 9.58k forks source link

How to use plugins in Vuex #2193

Closed serdariset closed 2 years ago

serdariset commented 2 years ago

I want to use my api plugin in Vuex. It's responding me 'undefined'. When i write console.log(this.$api.UserService) it's responding me 'undefined. But i can access Vue components this object. I was use this in Nuxt.js.

/plugins/api.js

import axios from "axios";
import jsCookie from "js-cookie";
import UserService from "../services/UserService";

const baseUrl = process.env.VUE_APP_API_URL;

const apiUser = baseUrl + "/api/user";
const api = axios.create({
  timeout: 1000,
  headers: {
    "X-Custom-Header": "foobar",
  },
});
api.interceptors.request.use(
  (config) => {
    config.headers.Authorization = `Bearer ${jsCookie.get("token")}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
api.UserService = new UserService(api, apiUser);

export default api

main.js

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import i18n from "./i18n";
import Vuelidate from "vuelidate";
import fontawesome from "./utils/fontawesome";
import api from "./plugins/api";
Vue.use(Vuelidate);
Vue.config.productionTip = false;
Vue.prototype.$api = api;

new Vue({
  fontawesome,
  router,
  store,
  i18n,
  render: (h) => h(App),
}).$mount("#app");

/store/login.js

  actions: {
    loginUser(_, payload) {
      this.$api.UserService.Login(payload.email, payload.password).then(
        (response) => {
          if (response.data.status) {
            console.log(response);
          }
        }
      );
    },
  }
vue-bot commented 2 years ago

Hello, thank you for taking time filling this issue!

However, we kindly ask you to use our Issue Helper when creating new issues, in order to ensure every issue provides the necessary information for us to investigate. This explains why your issue has been automatically closed by me (your robot friend!).

I hope to see your helper-created issue very soon!