在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ Vue 賦值問題

Vue 賦值問題

最近再學習 Vue.js想把 API 那里獲得的數(shù)據(jù)賦值給 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,
            }
        }
    };
回答
編輯回答
刮刮樂

這個問題你需要知道什么是異步執(zhí)行。
這個要講清楚不是三言兩語的事,詳細的建議你自己查下,我這里只簡單說下為什么 log 出來總是 a

請看下面的代碼,我在注釋里用數(shù)字標明這段代碼實際執(zhí)行的順序,可能與你原本所預期的有所不同:

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

補充

那么你想實現(xiàn)的這個效果應該怎么寫呢:

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

希望對你有幫助

2018年3月7日 01:27