Composition API에서 반응성 주입하는 다양한 방식

미랭군·2023년 4월 5일
0

Vue3 정리

목록 보기
2/3

Options API 방식으로 데이터 바인딩

<template>
	<h2> {{ username }} </h2>
</template>

<script>
export default {
	name: "TestComponent",
 	data() {
 		return {
  			username: "aaa",
 	}
}

Composition 방식으로 데이터 바인딩

반응성 없음

<template>
 <h2> {{ username }} </h2>
</template>

<script>
export default {
 name: "TestComponent",
 setup() {
 const username = "aaa"
 return {
  username,
 }
}

반응성 있음 reative 방식

object return 형으로 반응성 주입

<template>
 <h2> {{ state.username }} </h2>
</template>

<script>
import { reactive } from 'vue'
export default {
 name: "TestComponent",
 setup() {
 const state = reactive({                  //오브젝트에 반응성 주입
  username: 'aaa',
  age: 50
 })
 return {
  state
 }
}

반응성 있음 reactive, toRefs 방식

object return 형으로 반응성 주입 및 key값으로 바로 바인딩 가능하게 변경

<template>
 <h2> {{ username }} </h2>
 <h2> {{ age }} </h2>
</template>

<script>
import { reactive, toRefs } from 'vue'
export default {
 name: "TestComponent",
 setup() {
 const state = reactive({                  //오브젝트에 반응성 주입
  username: 'aaa',
  age: 50
 })
 return ...toRefs(state)
}
</script>

반응성 있음 ref 방식

단일형 데이터 return 형으로 반응성 주입

<template>
	<h2>handsome? {{ isNotUgly }}</h2>
</template>

<script>
import { ref } from 'vue'
export default {
	name: "TestComponent",
 	setup() {
 		let isHandsome = ref(false); //단일값에 반응성 주입
 		let isNotUgly = isHandsome;
 		isHandsome.value = true;

 		return { isNotUgly }
	}
</script>

반응성 있음 ref 방식 변경함수를 통한 바인딩 테스트

단일형 데이터 return 형으로 반응성 주입

<template>
	<h2>{{ username }}</h2>
 	<button @click="changeName">ChangeUserName</button>
</template>

<script>
import { ref } from 'vue'
export default {
	name: "TestComponent",
 	setup() {
 		let username= ref("Ronaldo"); //단일값에 반응성 주입
 		function changeName() {
  			username.value = "Messi"
 		}
 		isHandsome.value = true;

 		return { username, changeName }
	}
}
</script>
profile
개발자

0개의 댓글