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>