본문 바로가기

기타/vue js

Vue js 인스턴스 라이프사이클 예제

728x90

오늘은 vue 인스턴스의 라이프 사이클에 대해 공부해보도록 하겠습니다.

인스턴스의 라이프 사이클을 알면 app을 보다 디테일하게 다룰 수 있습니다.

때문에 반드시 알아야 합니다.

 

vue 인스턴스의 라이프사이클은

beforecreate() 인스턴스가 생성되기 전이다.->

created() 인스턴스가 생성되어 데이터를 사용할 수 있습니다.->

beforeMount() div태그 #app의 html 코드가 생성되기 전 상태->

mount()html코드가 div태그 #app에 html코드가 찍혀있는 상태->

beforeupdate() 데이터가 업데이트 되기 전->

updated()되고난후->

beforedestroy()해당 페이지를 종료하기 전->

destroy() 해당 페이지가 종료된 상태

<template>
  <div>
    <h1>this is Home page</h1>
    <p>{{names}}</p>
    <button v-on:click="dateupdate()">click</button>
  </div>
</template>

<script>
export default{
  data(){
   return{
     names:"balmostory"
    }
  },
  beforeCreate(){
    console.log("beforeCreate",this.names)
  },
  created(){
    console.log("created",this.names)
  },
  beforeMount(){
    alert("beforeMount")
  }
  ,
  mounted(){
    alert("mounted")
  },
  beforeUpdate(){
    alert("beforeUpdate")
  },
  updated(){
    alert("updated")
  },
  beforeDestroy(){
    alert("beforeDestroy")
  },
  destroyed(){
    alert("destroyed")
  },
  methods:{
    dateupdate(){
      this.names="hihihi";
    }
  }
}
</script>


<style scoped>
h1{
  color: red;
  font-size: 20px;
}
</style>

코드를 위와 같이 수정해주세요.

페이지를 열고 console을 보면 다음과 같이 나와있습니다.

beforecreate에서는 데이터에 접근할 수 없고 created 후에 접근할 수 있습니다.

beforMount alert가 나오고 확인을 누르면 아래와 같이 div에 코드가 생성되면서 mounted alert가 나옵니다.

 

 

click을 눌러 데이터를 바꿔주면 다음과 같이 beforeupdate alert가 나오고

확인을 누르면 updated alert가 나오고 확인을 누르면 데이터가 변합니다.

 

about 페이지를 누르면 beforedestroy alert가 나오고 확인을 누르면

 

destroyed alert가 나옵니다. 확인을 누르면 about페이지로 이동합니다.

728x90

'기타 > vue js' 카테고리의 다른 글

vue js todo 리스트 튜토리얼(2)  (0) 2020.10.06
vue js todo 리스트 튜토리얼(1)  (0) 2020.10.05
vue js slot 기본 예제  (0) 2020.10.03
vue js props  (0) 2020.10.02
vue js 싱글 파일 컴포넌트 예시  (0) 2020.09.30