簡體   English   中英

Vue.js Mounted() 中的更新數據不起作用

[英]Update data in Vue.js Mounted() doesn't work

我嘗試在我的 Vue.js 組件中更新我安裝的部分中的一些數據。 這是我的代碼:

  methods: {
    initData() {
      const self = this;

      axios
        .get("/checkAuthentification")
        .then((response) => {
          (self.userFields.userAuthenticated = response.data),
            console.log("method"),
            console.log(self.userFields.userAuthenticated),
            console.log("reponse"),
            console.log(response.data);
        })
        .catch((error) => {
          (self.errors = error.response.data.errors || {}),
            console.log(self.errors);
        });

      console.log("between");

      console.log(self.userFields.userAuthenticated);

      if (self.userFields.userAuthenticated == "true") {
        axios
          .get("/getAuthenticatedUserData")
          .then((response) => {
            (self.userId = String(response.data.id)),
              (self.userFields = response.data),
              console.log("user data"),
              console.log(response.data);
          })
          .catch((error) => {
            (self.errors = error.response.data.errors || {}),
              console.log(self.errors);
          });
      }
    },
  },
  mounted() {
    this.initData();
  },

在第一個 axios 調用中,它運行良好,兩個控制台日志給出了預期值“true”。 但是在兩者之間的下一個console.log上,它顯示“未定義”。 在第一次 axios 調用之后,用戶字段不會更新。 我不明白,因為我在表單上的提交按鈕上做了同樣的事情,而且效果很好。 我在這里問是因為我查看了其他帖子,答案總是使用 const=this,我這樣做了。 謝謝您的幫助 !

要首先回答您的問題,您必須了解 Javascript 中異步操作的性質。 我會盡力解釋,但會留下這個鏈接,以防你想閱讀更多關於它的信息

在您的示例中,您有:

axios.get('/checkAuthentification').then(response =>{
  console.log('CHecked authentication')
  ...
})

console.log('between');

console.log(self.userFields.userAuthenticated);

當您執行axios.get時,會調用異步操作(異步 = 不會等待代碼繼續執行的答案)。 您將聯系您的后端服務器,只有當您收到答案時, console.log('checked authentication')才會運行,但與此同時(請記住axios.get是異步的) console.log('between'); AND console.log(self.userFields.userAuthenticated); console.log('between'); AND console.log(self.userFields.userAuthenticated); 將在您從后端服務器收到答案之前執行。

我們如何解決這個問題我們可以用兩種方法解決這個問題。 第一個將是更舊的方法 - 等待由then關鍵字解決的承諾

axios
  .get('/checkAuthentification')
  .then(response =>{
    console.log('CHecked authentication')
  
    console.log('between');

    console.log(self.userFields.userAuthenticated);
    
    return response;
  })
  .then(() => {
    // do more operations after promise was resolved
  })

或者我們可以采用更現代的方式——我們可以使用 async/await。

async initData() {
  const response = await axios.get('/checkAuthentification');

  console.log('CHecked authentication')
  
  console.log('between');

  console.log(self.userFields.userAuthenticated);
}
state: { userFields: { userAuthenticated: false, ... } }, methods: { initData() { const self = this; axios .get("/checkAuthentification") .then((response) => { (self.userFields.userAuthenticated = response.data), console.log("method"), console.log(self.userFields.userAuthenticated), console.log("reponse"), console.log(response.data); }) .catch((error) => { (self.errors = error.response.data.errors || {}), console.log(self.errors); }); }, getUserData() { if (this.userFields.userAuthenticated) { axios .get("/getAuthenticatedUserData") .then((response) => { (self.userId = String(response.data.id)), (self.userFields = response.data), console.log("user data"), console.log(response.data); }) .catch((error) => { (self.errors = error.response.data.errors || {}), console.log(self.errors); }); } } }, watch: { 'userFields.userAuthenticated': function() { this.getUserData() } }, mounted() { this.initData(); },

暫無
暫無

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

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