[Vue3] Vue3 알아보기
Vue3: 2020년 09월 18일 릴리즈된 vue코어 라이브러리
1. Vue3 의 특징
● 강화된 타입스크립트 지원 (세부적 type 선언 가능)
● 코드 재사용 가능한 setup api 사용
● 기존 optional api 방식과 composition api 방식 모두 사용 가능
* composition api: 데이터,로직별로 분리 가능, reactive보다는 ref지향
2. Vue2 와의 차이점
◎ 2.0버전:
●컴포넌트의 옵션을 data, computed, methods, watch 등으로 구분하여 사용
● creaetd, Mounted , updated 등의 메소드 사용
● 템플릿 (template) 안에 루트 엘리먼트 하나만 종속 가능
◎ 3.0버전:
● 컴포넌트 옵션과 beforeCreate, created 메소드를 setup api 내 자유롭게 선언하여 사용
● 메소드 변경
beforeMount → onBeforeMount
mounted → onMounted
beforeUpdate → onBeforeUpdate
updated → onUpdated
beforeUnmount → onBeforeUnmount
unmounted → onUnmounted
errorCaptured → onErrorCaptured
renderTracked → onRenderTracked
renderTriggered → onRenderTriggered
activated → onActivated
deactivated → onDeactivated
● 템플릿 (template) 안에 여러개의 루트 엘리먼트 종속 가능
3. Vue2, Vue3 비교예시
◎ composition api 사용 X
// vue2
<template>
<div>
<p>{{ clickMsg }}</p>
<button @click="changeMsg">hi에서 hello로 변경</button>
</div>
</template>
<script>
export default {
data() {
return { message: "hi" };
},
methods: {
changeMsg() {
this.message = "hello"; // button 클릭 시 msg 텍스트 변경
}
}
};
</script>
<style lang="scss" scoped></style>
// vue3
<template>
<div>
<p>{{ clickMsg }}</p>
<button @click="changeMsg">hi에서 hello로 변경</button>
</div>
</template>
<script>
import { defineNuxtComponent } from "#app";
export default defineNuxtComponent({
data() {
return { message: "hi" };
},
methods: {
changeMsg() {
this.message = "hello"; // button 클릭 시 msg 텍스트 변경
}
}
});
</script>
<style lang="scss" scoped></style>
◎ composition api 사용 O
// vue2
<template>
<div>
<p>{{ clickMsg }}</p>
<button @click="changeMsg">hi에서 hello로 변경</button>
</div>
</template>
<script>
import { ref } from "@vue/composition-api";
export default {
setup() {
const message = ref("hi");
const changeMsg = () => (message.value = "hello");
return { message, changeMessage };
}
};
</script>
<style lang="scss" scoped></style>
// vue3
<template>
<div>
<p>{{ clickMsg }}</p>
<button @click="changeMsg">hi에서 hello로 변경</button>
</div>
</template>
<script>
import { defineNuxtComponent } from "#app";
export default defineNuxtComponent({
setup() {
const message = ref("hi");
const changeMsg = () => (message.value = "hello");
return { message, changeMessage };
}
});
</script>
<style lang="scss" scoped></style>
참고: https://vuejs.org/api/composition-api-lifecycle.html#onupdated