简体   繁体   English

Vue.js Mounted() 中的更新数据不起作用

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

I try to update some data in my mounted part, in my Vue.js component.我尝试在我的 Vue.js 组件中更新我安装的部分中的一些数据。 Here is my code:这是我的代码:

  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();
  },

In the first axios call, it works perfectly, the two console log give the expected value "true".在第一个 axios 调用中,它运行良好,两个控制台日志给出了预期值“true”。 But on the next console.log after between, it says 'undefined'.但是在两者之间的下一个console.log上,它显示“未定义”。 Thue userFields doesn't update after the firt axios call.在第一次 axios 调用之后,用户字段不会更新。 I don't understand because i did the same thing on a submit button on a form, and it worked perfectly.我不明白,因为我在表单上的提交按钮上做了同样的事情,而且效果很好。 I ask here because I looked other posts and the answer is always to use const=this, which I did.我在这里问是因为我查看了其他帖子,答案总是使用 const=this,我这样做了。 Thank you for your help !谢谢您的帮助 !

To answer your questions first you would have to understand the nature of asynchronous operations in Javascript.要首先回答您的问题,您必须了解 Javascript 中异步操作的性质。 I will try my best to explain but will leave this link in case you would like to read more about it我会尽力解释,但会留下这个链接,以防你想阅读更多关于它的信息

On your example you have:在您的示例中,您有:

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

console.log('between');

console.log(self.userFields.userAuthenticated);

When you do the axios.get what happens is that an asynchornous operation will be called (asynchornous = won't wait for the answer for the code to continue execution).当您执行axios.get时,会调用异步操作(异步 = 不会等待代码继续执行的答案)。 You will contact your backend server and ONLY when you receive an answer the console.log('checked authentication') will run but in the meantime (remember axios.get is asynchronous) the console.log('between'); AND console.log(self.userFields.userAuthenticated);您将联系您的后端服务器,只有当您收到答案时, console.log('checked authentication')才会运行,但与此同时(请记住axios.get是异步的) console.log('between'); AND console.log(self.userFields.userAuthenticated); console.log('between'); AND console.log(self.userFields.userAuthenticated); will execute before you receive an answer from the backend server.将在您从后端服务器收到答案之前执行。

How can we solve this We can solve this with two approaches.我们如何解决这个问题我们可以用两种方法解决这个问题。 The first one would be the more old approach - waiting for promises to resolve by the then keyword第一个将是更旧的方法 - 等待由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
  })

Or we can do a more modern way - we can use async/await.或者我们可以采用更现代的方式——我们可以使用 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