[TIL] v-model and properties events

JIEUN YANG·2022년 8월 11일
0

component 와 v-model

component사용 시 v-model 하나로 props & emit의 효과를 제공할 수 있다.

How To Add v-model Support to Custom Vue.js Components | DigitalOcean


💡 정리하자면 이렇다. v-model은 v-bind와 v-on의 기능의 조합이며, @input안에서는 화살표 함수로 바인딩 할 값을 명시해줘야 한다
v-model="inputValue" === :value="inputValue" @input="(e) => (inputValue = e)"
  • 주의할 점은, 1) emit으로 전달한 값의 타입에 따라 input 안 데이터 할당 구조는 달라짐 2) v-model로 바인딩 할 때 emit 구문에서 input(default) 이라는 이름으로 전달됨 만약 이벤트명을 바꾸고 싶다면 model 안에 정의 필요
    model: {
      event: 'customEvent',
    },
      props: {
        title: { type: String },
        radioButtonsArray: {
          type: Array,
          default: () => {
            return []
          },
        },

바로 아래 토글의 내용과 역설된 내용처럼 들릴 수 있지만

엘리먼트에 따라 다른 이벤트를 제공하는 것은 HTML에서 input에 해당되기 때문에 v-model안emit 구문의 input(default) 가 된다는 내용은 포인트가 다르다.



properties and events in different v-model


💡 * HTML 입력 요소의 종류에 따라 v-model 속성이 다르다

1. text, textarea - 속성값의 default로 value, 이벤트로 input 을 제공

<input type="input" @input="updateInput" />
methods: {
    updateInput(e) {
      console.log(e.target.value) --> 
			/**
       * input이벤트가 실행될 때(=text입력할 때)마다
       * console에 입력된 값(=UI에 보이는 text값)을 확인할 수 있다
       */
      this.$emit('input', e.target.value)
    },
  },

2. checkboxes, radiobuttons - checked / change

<input type="checkbox" id="label1" @change="updateChecked" />
methods: {
    updateChecked(e) {
      console.log(e.target.value)
      console.log(e.target.checked)
      /**
       * change이벤트가 실행될 때(=checkbox클릭할 때)마다
       * console에 입력된 값을 확인해보면
       * e.target.value값은 "on"
       * e.target.checked 값은 true/false 가 번갈아가며 찍힌다
       */
      this.$emit('input', e.target.value)
    },
  },
💡 type input과 다르게 checkbox에서는 target 객체 안의 value값이 "on" 임을 확인할 수 있다

3. select fields - value / change

<input type="select" @change="changeValue" />
profile
violet's development note

0개의 댓글