簡體   English   中英

VUE 3 - 在其他方法中使用獲取的數據

[英]VUE 3 - use fetched data in other method

您好,我正在嘗試在 VUE 3 中以其他方法使用獲取的數據。我只想在應用程序啟動時加載所有數據,然后在代碼中多次使用它們。 我的代碼是:

const app = Vue.createApp({
 data() {
  return {
   dataAll : [],
  };
 },

 mounted() {
  this.getData();
  this.otherFunction();
 },

 methods: {
  getData() {
   fetch('app/api.php')
   .then((response) => response.json())
    .then((data) => {
      this.dataAll = data;
      //this.dataAll = JSON.parse(JSON.stringify(data));
    });
  },
  otherFunction() {
   console.log(this.dataAll);
  }
});

但是控制台顯示Proxy {} - Array(0) 我在哪里犯了錯誤? 謝謝

fetch 函數是異步的,在調用 otherFunction 之前不需要等待 getData 函數解析。

在調用依賴於數據的其他函數之前等待承諾解決:

const app = Vue.createApp({
  data() {
    return {
      dataAll: [],
    };
  },
  mounted() {
    this.getData().then(() => {
      this.otherFunction();
    })
  },
  methods: {
    getData() {
      return fetch('app/api.php')
        .then((response) => response.json())
        .then((data) => {
          this.dataAll = data;
        });
    },
    otherFunction() {
      console.log(this.dataAll);
    }
  }
});

或者你也可以使用異步等待

const app = Vue.createApp({
  data() {
    return {
      dataAll: [],
    };
  },
  async mounted() {
    await this.getData();
    this.otherFunction();
  },
  methods: {
    async getData() {
      const data = await fetch(
        "app/api.php"
      ).then((response) => response.json());
      this.dataAll = data;
    },
    otherFunction() {
      console.log(this.dataAll);
    }
  }
});

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#using_the_fetch_api

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises#async_and_await

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM