programing

created() 라이프 사이클훅의 vue 비동기 호출

sourcetip 2022. 7. 15. 23:24
반응형

created() 라이프 사이클훅의 vue 비동기 호출

아래 메서드를 호출해야 합니다.created()이 목적을 위해서, 저는 이 모든 것들을created()~하듯이async. Vue 매뉴얼에 따르면created()동시에 호출됩니다.Will Vue 프레임워크awaitcreated()어떤 레이스 조건도 피하려고요?

this.isAuthenticated = await authService.isAuthenticated();

Vue.config.productionTip = false;

function tm(ms, msg) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(msg);
    }, ms);
  });
}

new Vue({
  async beforeCreate() {
    console.log(await tm(1000, "BEFORE CREATE"));
  },
  async created() {
    console.log(await tm(2000, "CREATED"));
  },
  async beforeMount() {
    console.log(await tm(3000, "BEFORE MOUNT"));
  },
  async mounted() {
    console.log(await tm(4000, "MOUNTED"));
  }
}).$mount("#app");
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

비동기 기능이 완료될 때까지 기다릴 필요가 있는 경우.기본적으로 Vue 인스턴스를 생성하기 전에 기다릴 수 있습니다.이것은 항상 사용할 수 있는 것은 아니지만, 이 질문에서와 같은 경우에는 사용할 수 있으며, 대기하지 않은 비동기 라이프 사이클 훅을 설치하는 것보다 더 견고합니다.

Vue.config.productionTip = false;

// mock service
const authService = {
  isAuthenticated: () => new Promise((r) => setTimeout(() => r(true), 2000))
};


// async iife to await the promise before creating the instance
(async() => {
  const isAuthenticated = await authService.isAuthenticated();
  new Vue({
    data: {
      isAuthenticated
    },
    created() {
      console.log('authenticaed:', this.isAuthenticated);
    },
  })
})().catch(console.warn);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

언급URL : https://stackoverflow.com/questions/59310803/vue-async-call-in-created-lifecycle-hook

반응형