Vue 赋值问题

最近再学习 Vue.js想把 API 那里获得的数据赋值给 Post_List,但是打印出来变量一直没变 打印出来始终是 a

对 JS 不太了解,望大家指点下

 export default {
        data() {
            const Login_Scope = this;
            let Post_List = 'a';
            axios.get('/api/postList')
                .then(function (response) {
                    console.log(response);
                    Login_Scope.Post_List = response.data;
                })
                .catch(function (error) {
                    // vm.answer = 'Error! Could not reach the API. ' + error
                });
            console.log(Post_List);
            return {
                postList: Post_List,
            }
        }
    };
阅读 2.2k
1 个回答

这个问题你需要知道什么是异步执行
这个要讲清楚不是三言两语的事,详细的建议你自己查下,我这里只简单说下为什么 log 出来总是 a

请看下面的代码,我在注释里用数字标明这段代码实际执行的顺序,可能与你原本所预期的有所不同:

const Login_Scope = this;                    // 1
let Post_List = 'a';                         // 2
axios.get('/api/postList')                   // 3
  .then(function (response) {
    console.log(response);                   // 6
    Login_Scope.Post_List = response.data;   // 7
  })
  .catch(function (error) {
    // vm.answer = 'Error! Could not reach the API. ' + error
  });
  console.log(Post_List);                    // 4
  return {                                   // 5
    postList: Post_List,
  }
}

具体为什么会这样,还是先了解下异步请求Promise

补充

那么你想实现的这个效果应该怎么写呢:

export default {
  data () {
    return {
      postList: 'a',
    }
  },
  // 或者 created
  mounted () {
    const Login_Scope = this;
    axios.get('/api/postList') 
      .then(function (response) {
        Login_Scope.postList = response.data;
        console.log(Login_Scope.postList); 
      })
      .catch(function (error) {
        // vm.answer = 'Error! Could not reach the API. ' + error
      });
  }
}

希望对你有帮助

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题