FE/Vue.js

[Vue] 데이터 바인딩 (ref, reactive) / 조건문, 반복문 (v-if, v-for) / v-model

셰욘 2024. 12. 20. 16:20
728x90

ref, reactive?

<template>와 연동되어 JS의 값이 바뀌면 바로 <template>에서 보여지는 내용도 바뀌는 변수

= 데이터 바인딩 (JS 코드와 HTML 태그를 연결해주는 것)

 

ref : 숫자나 문자열 같은 기본형 변수

reactive : 객체나 배열 같은 참조형 변수

 


ref

기본 타입의 값을 이용해  반응성을 가진 데이터를 생성할 때 사용

 

ref 변수 생성

import { ref } from 'vue';

const message = ref('안녕하세요');
const x = ref(10);

 

 

ref 값 변경

값을 변경하는 함수를 만들어준다.

const x = ref(10);

const changeValue = () => {
	x.value = x.value + 1;
}

 


버튼을 클릭 시 함수가 실행될 수 있게 등록해준다.

<template>
  <p>{{ message }}</p>
  <button @click="changeMessage">버튼1</button>
</template>

 


reactive

객체에 대한 반응성을 가진 데이터를 만들 때 사용

 

reactive 변수 생성

import { reactive } from 'vue';

const obj = reactive({ name: "psy", num: 0 });

 

reactive 값 변경

함수를 따로 만들지 않고 바로 변경할 수 있다.

<template>
  <p>{{ obj.num }}</p>
  <button @click="obj.num = obj.num + 1">버튼</button>
</template>

 

 

확장 프로그램에서 변수를 확인할 수 있다.

 


조건문 (v-if)

조건부로 블록을 렌더링할 때 사용한다.

v-if 안에 들어간 값에 따라 바뀐다.

const isTrue = ref(true);
<div v-if="isTrue">
  <p>{{ message }}</p>
</div>

 


반복문 (v-for)

v-for 안에 반복할 내용을 넣어서 사용한다.

const objList = reactive({
  objs: [
    {id:1, name:'test01'},
    {id:2, name:'test02'},
    {id:3, name:'test03'}
  ]
})
<div v-for="obj in objList.objs">
  <h2>{{ obj.id }}</h2>
  <h3>{{ obj.name }}</h3>
</div>

v-model

함수를 따로 만들어주지 않아도 변수로 바로 연결이 되게 하는 역할

입력하는 값이 자동으로 데이터와 연결된다.

const value = ref('');
const isCheck = ref(true);
<template>
  <p v-if="isCheck">체크함</p>
  <input type="text" v-model="value">
  <input type="checkbox" id="checkbox" v-model="isCheck">
  <label for="checkbox">체크박스</label>
</template>

 

 

728x90