繁体   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