📍Reactive state: reactive()
- state가 바뀌면 HTML도 자동으로 업데이트됨
- 이 state는 reactive 성격을 띔
- Vue.js의 reactive() API를 활용하여 reactive state 선언 가능
- reactive() API로 만들어진 객체들은 JS 프록시 객체들이고 일반 객체들처럼 작동함
import { reactive } from "vue";
const counter = reactive({
count: 0,
});
console.log(counter.count); // 0
counter.count++;
📍Reactive state: ref()
- reactive()는 객체에 대해서만 작동(배열, Map, Set 포함)
- 반면 ref()는 어떤 타입에든 자유롭게 사용 가능
- ref()로 만든 state는 객체이고, 내부의 value 프로퍼티로 참조 가능
import { ref } from "vue";
const message = ref("Hello World!");
console.log(message.value); // "Hello World!"
message.value = "Changed";
📍Reactive state 렌더링
- <script setup> 블럭에서 선언된 reactive state는 <template> 블럭에서 자유롭게 참조 가능
- {{ }} 형태(mustache 문법)로 state를 <template> 블럭에서 사용
<h1>{{ message }}</h1>
<p>Count is: {{ counter.count }}</p>
- <template> 블럭에서 ref() 값을 참조할 때는 value 프로퍼티로 참조하지 않아도 됨
- mustache 내부에서는 JS 표현식 사용 가능
<h1>{{ message.split('').reverse().join('') }}</h1>