오늘의 공부(2022.07.29)

조지성·2022년 7월 29일
0

TIL

목록 보기
65/78
post-thumbnail

양방향 바인딩

v-model

  • 입력 요소의 상태자바스크립트의 상태동기화해야 하는 경우 사용
  • textarea , checkbox , radio , select
<template>
  <div>
    <h2>input value</h2>
    <!-- <input type="text" :value="inputValue" @input="event=>inputValue = event.target.value"> -->
    <input type="text" v-model="inputValue" />
    <div>{{ inputValue }}</div>

    <h2>textarea value</h2>
    <!-- <textarea :value="textareaValue" @input="event=>inputValue = event.target.value"></textarea> -->
    <textarea v-model="textareaValue"></textarea>
    <div>{{ textareaValue }}</div>

    <h2>check value</h2>
    <label for="checkbox">{{ checkboxValue }}</label>
    <!-- <input type="checkbox" id="checkbox" :checked="checkboxValue"
      @change="event => { checkboxValue = event.target.checked }"> -->
    <input type="checkbox" id="checkbox" v-model="checkboxValue">

    <h2>radio value</h2>
    <!-- <label>
      <input type="radio" name="type" value="O" 
      :checked="radioValue === 'O'" @change="event=>radioValue = event.target.value">
      O형
    </label>
    <label>
      <input type="radio" name="type" value="A" 
      :checked="radioValue === 'A'" @change="event=>radioValue = event.target.value">
      A형
    </label> -->
    <label>
      <input type="radio" name="type" value="O" v-model="radioValue">
      O형
    </label>
    <label>
      <input type="radio" name="type" value="A" v-model="radioValue">
      A형
    </label>
    <div>{{ radioValue }}</div>

    <h2>select value</h2>
    <!-- <select :value="selectValue" @change="event=>selectValue = event.target.value">
      <option value="html">HTML 수업</option>
      <option value="css">CSS 수업</option>
      <option value="javascript">JavaScript 수업</option>
    </select> -->
    <select v-model="selectValue">
      <option value="html">HTML 수업</option>
      <option value="css">CSS 수업</option>
      <option value="javascript">JavaScript 수업</option>
    </select>
    <div>{{ selectValue }}</div>
  </div>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const inputValue = ref(null);

    const textareaValue = ref(null);

    const checkboxValue = ref(true);

    const radioValue = ref('O');

    const selectValue = ref('html');
    return {
      inputValue,
      textareaValue,
      checkboxValue,
      radioValue,
      selectValue,
    }
  }
}
</script>

<style lang="scss" scoped>
</style>

v-model 수식어

.lazy

기본적으로, v-model은 각 input 이벤트 후 입력과 데이터를 동기화

 lazy 수식어를 추가하여 change 이벤트 이후에 동기화

<input v-model.lazy="text" />

.number

사용자 입력이 자동으로 number 타입으로 형변환

<input v-model.number="text" />

.trim

사용자가 입력한 내용에서 자동으로 앞뒤 공백을 제거하는 트림처리

<input v-model.trim="text" />
profile
초보 개발자의 성장기💻

0개의 댓글