라이프사이클 : 특정 시점별 자동으로 실행되는 메서드
생성 -> 부착 -> 수정 -> 삭제 총 4가지 시점이 있습니다.
각 컴포넌트별 특정 시점에 동작해야할 경우들이 발생하기 때문이다.
생성 : created() - 미리 데이터를 가져올 경우 사용
부착 : mounted() - DOM에 접근하여 DOM 변경 작업을 할 때 사용, 부착은 생성 후 실행되는 메서드로 데이터 생성 및 화면이 모두 만들어진 상태이므로, created에서 가능한 모든 것들이 가능하다.
created()
<template>
<div class="home">
<h1>hello vue.js</h1>
<!-- loading일 때 -->
<div v-if = "loading">로딩중...</div>
<!-- 로딩이 끝났을 때 데이터 가져오기 -->
<div v-else>
<div v-for = "t in todo" v-bind:key = "t.id">
{{ t }}
</div>
</div>
</div>
</template>
<script>
// npm i axios 입력 후 axios 가져오기
import axios from "axios"
export default {
name: "Home",
// vue에서 데이터를 정의하는 곳
data(){
return{
todo: [],
loading: true
}
},
// 데이터 관리 및 데이터를 가져온다, axios 호출 등을 해당 부분에서 진행
async created(){
try{
// 비동기로 json 파일들 가져와 todo 변수에 넣기
const response = await axios.get("https://jsonplaceholder.typicode.com/todos/");
this.todo = response.data;
// 비동기로 정보를 다 받아왔다면 loading = false
this.loading = false;
}catch(error){
console.log(error);
}
}
}
</script>
<style scoped>
</style>
결과
json 파일들을 가져온다.
mounted()
<template>
<div class="home">
<h1>hello vue.js</h1>
<!-- loading일 때 -->
<div v-if = "loading">로딩중...</div>
<!-- 로딩이 끝났을 때 데이터 가져오기 -->
<!-- DOM에 접근할 일이 생길때 ref 사용 -->
<div v-else>
<div v-for = "t in todo" v-bind:key = "t.id">
{{ t }}
</div>
</div>
<!-- 직접적인 접근이 필요할때 ref 사용 -->
<input ref="input-ref">
<div ref="div-ref">aaa</div>
</div>
</template>
<script>
// npm i axios 입력 후 axios 가져오기
import axios from "axios"
export default {
name: "Home",
// vue에서 데이터를 정의하는 곳
data(){
return{
todo: [],
loading: true
}
},
// 데이터를 가져온다, axios 호출 등을 해당 부분에서 진행 , 데이터 관리
async created(){
console.log("created: 데이터가 생성되었으나 화면에 부착되지는 않는다.")
console.log(this.todo);
// ref 접근
// this.$refs.ref로 선언한 변수이름
// this.$refs.input-ref -> -가 문장이 분리되었다고 인식하기 때문에 []안에 넣어서 객체에 접근
console.log(this.$refs['input-ref'])
console.log(this.$refs['div-ref'])
try{
// 비동기로 json 파일들 가져와 todo 변수에 넣기
const response = await axios.get("https://jsonplaceholder.typicode.com/todos/");
console.log(response);
this.todo = response.data;
// loading 후 false
this.loading = false;
}catch(error){
console.log(error);
}
},
mounted(){
console.log("mounted : 화면에 부착된 후")
// vue에서 화면에 접근 해야할 상황에 사용된다.
// 특정 이벤트등을 활용할때에는 DOM에 직접 접근 해야하는 경우가 생긴다.
// document.querySelecotr 를 사용하는게 아닌 ref를 활용할 것이다!
console.log(this.$refs['input-ref'])
console.log(this.$refs['div-ref'])
const div = this.$refs['div-ref'];
div.style.color = "Blue";
this.$refs['input-ref'].focus()
}
}
</script>
<style scoped>
</style>
결과