簡體   English   中英

如何從 vue 組件獲取常規 js 文件中的數據值?

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

我有組件 MyComponent.vue 我有不斷變化的數據值。 我想將此值傳遞給 javascript 文件(js 文件應該知道每次值的變化)

我為什么要這樣做? 因為我的常規 js 文件是 axios 方法的服務層。 我可以在許多其他組件中導入此文件。 該文件包含 axios 方法和 url 是動態的。 我希望這些網址取決於數據變量。 此數據變量來自 MyComponent.js

所以主要目標是制作依賴於數據變量的 axios 的動態 url

我嘗試了一些代碼,但它不起作用,因為 js file(CategoryService.js) 對this.categoryNumber

我的組件.vue:

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

類別服務.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();

所以通過一些重構,你可以很容易地讓它工作。

首先,我會將您的 class 的 if/else 邏輯放入其中。

為了方便和可擴展性,我會使用 Vuex 商店來跟蹤您的 categoryNumber 並在您的所有組件中共享它。

然后我會將我的服務綁定到我的 Vue 實例,這樣我就可以輕松地在我的所有組件以及商店中訪問它,並將后者作為參數傳遞給我的 class。

對於最后一部分,我不知道 http-common 文件中的邏輯,所以我將向您展示的代碼有點討厭。 但是根據您是否將“http”綁定到 axios,您可以使用axios 攔截器在每個請求中調用getCategoryNumber()方法。

這是我將 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>

感謝@Solar,我剛剛為所有 url 添加了一個參數並將類別的數量添加到它

類別服務.js:

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

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

    }

函數.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