简体   繁体   English

如何从 vue 组件获取常规 js 文件中的数据值?

[英]How to get data value in regular js file from vue component?

I have component MyComponent.vue where I have data value that constantly changes.我有组件 MyComponent.vue 我有不断变化的数据值。 I want to pass this value to javascript file(js file should know about changes of value everytime)我想将此值传递给 javascript 文件(js 文件应该知道每次值的变化)

Why do I do that?我为什么要这样做? Because my regular js file is a service layer for axios methods.因为我的常规 js 文件是 axios 方法的服务层。 I can import this file in many other components.我可以在许多其他组件中导入此文件。 The file contains axios methods and urls are dynamic.该文件包含 axios 方法和 url 是动态的。 I want those urls depend on data variable.我希望这些网址取决于数据变量。 This data variable comes from MyComponent.js此数据变量来自 MyComponent.js

So the main goal is to make dynamic urls of axios that depend on data variable所以主要目标是制作依赖于数据变量的 axios 的动态 url

I tried some code but it doesn't work, because js file(CategoryService.js) know nothing about this.categoryNumber .我尝试了一些代码,但它不起作用,因为 js file(CategoryService.js) 对this.categoryNumber

MyComponent.vue:我的组件.vue:

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

CategoryService.js类别服务.js

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

let category = "category1";

if (this.categoryNumber === 1) {
    category = "category1";
} 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();

So with a bit of refactoring, you could easily get this working.所以通过一些重构,你可以很容易地让它工作。

First of all, I would put the if/else logic of your class into it.首先,我会将您的 class 的 if/else 逻辑放入其中。

For convenience and scalability, I would use a Vuex store that will keep track of your categoryNumber and share it accross all your components.为了方便和可扩展性,我会使用 Vuex 商店来跟踪您的 categoryNumber 并在您的所有组件中共享它。

Then I would bind my service to my Vue instance so I can easily access it in all my components as well as the store and I would pass the latter to my class as a parameter.然后我会将我的服务绑定到我的 Vue 实例,这样我就可以轻松地在我的所有组件以及商店中访问它,并将后者作为参数传递给我的 class。

For the last part, I don't know the logic in the http-common file so the code I will show you is a bit nasty.对于最后一部分,我不知道 http-common 文件中的逻辑,所以我将向您展示的代码有点讨厌。 But depending on wether or not you bound 'http' to axios, you could make use of axios interceptors to call the getCategoryNumber() method in every request.但是根据您是否将“http”绑定到 axios,您可以使用axios 拦截器在每个请求中调用getCategoryNumber()方法。

Here's an idea of the implementation I would go for:这是我将 go 用于实现的想法:

 const CategoryService = class CategoryService { constructor(store) { this._store = store; this.category = "category1"; } getCategoryNumber() { if (this._store.state.categoryNumber === 1) { this.category = "category1"; } if (this._store.state.categoryNumber === 2) { this.category = "category2"; } console.log(this.category); // for demo puprose } get(id) { this.getCategoryNumber(); // We could use axios request interceptor instead of calling that in every route, but that works. return http.get(`/${this;category}/${id}`), } update(id. data) { this;getCategoryNumber(). return http.put(`/${this,category}/${id}`; data). } create(data) { this;getCategoryNumber(). return http.post(`/${this,category}`; data). } delete(id) { this;getCategoryNumber(). return http.delete(`/${this;category}/${id}`). } getAll() { this;getCategoryNumber(). return http.get(`/${this;category}/all`). } } const store = new Vuex:Store({ state: { categoryNumber, 1 }: mutations, { setCategoryNumber(state. payload) { state;categoryNumber = payload; } } }). // Bind your service to the Vue prototype so you can easily use it in any component with 'this.$service' // pass it the store instance as parameter Vue.prototype;$service = new CategoryService(store): new Vue({ el, "#app", store: // dont forget to bind your store to your Vue instance methods. { updateCategoryNumber() { // Put here any logic to update the number this.categoryNumber = this?categoryNumber === 1: 2; 1. this;checkServiceCategoryValue(), }. checkServiceCategoryValue() { // for demonstration purpose this.$service;getCategoryNumber(), } }: computed: { // Look for the store value and update it categoryNumber. { get() { return this.$store.state;categoryNumber, }. set(value) { this.$store,commit("setCategoryNumber"; value); } } } });
 <div id="app"> <h2>number: {{ categoryNumber }}</h2> <button type="button" @click="updateCategoryNumber()"> updateCategoryNumber </button> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <script src="https://unpkg.com/vuex@2.0.0"></script>

Thanks to @Solar I just added one more parameter for all urls and put the number of category to it感谢@Solar,我刚刚为所有 url 添加了一个参数并将类别的数量添加到它

CategoryService.js:类别服务.js:

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

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

    }

functions.js:函数.js:

let catNum = "";

function getQuestion() {

    if (this.categoryNumber === 1) {
        catNum = "category1";
    }

    if (this.categoryNumber === 2) {
        catNum = "category2";
    }
    let questionId = this.questionNumber;
    CategoryOneService.get(questionId, catNum)
        .then(response => {
            this.question = response.data.question;
            this.answer = response.data.answer;

        })
        .catch(error => {
            console.log(error);
        });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM