P
P
postya2020-07-14 14:16:27
Vue.js
postya, 2020-07-14 14:16:27

How to get variable value of one file in another javascript file?

There is a vue component MyComponent.vue, in which there is a variable, its value is constantly changing
There is a regular javascript file CategoryService.js, in which methods for axios are written, this file is a kind of service layer, which I then import in the desired component and use the axios methods .

I need a variable from the component to somehow get into this file. I need to get the value of this variable. All urls in this file are dynamic and they will be based on the value of this variable

This CategoryService.js file is not a component but a normal javascript file

How to get this variable?

Here is what I tried to do, but the categoryNumber variable is undefined:

MyComponent.vue:

<script>
export default {
data() {
return {
categoryNumber: 1
   }
  }
}
</script>


CategoryService.js:

import http from "../../../http-common";

let category = "category1";

if (this.categoryNumber === 1) {
  category = "category1";
} else if (this.categoryNumber === 2) {
  category = "category2";
}

class CategoryService {
  get(id) {
    return http.get(`/${category}/${id}`);
  }

  update(id, data) {
    return http.put(`/${category}/${id}`, data);
  }

  create(data) {
    return http.post(`/${category}`, data);
  }

  delete(id) {
    return http.delete(`/${category}/${id}`);
  }

  getAll() {
    return http.get(`/${category}/all`);
  }
}

export default new CategoryService();

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question