Programming/Vue.js

[Vue 2] v-model과 .sync의 차이점

stein 2021. 10. 18. 22:54

vue 관련 라이브러리들을 사용하다보면 변수.sync 로 작성된 코드들을 자주 만난다.

 

그냥 라이브러리 문법인가 보다 했는데 vue2->vue3 Migration Guide를 확인하는데 첫 번째 breaking change가 다음과 같다.

v-model usage on components has been reworked, replacing v-bind.sync

  

v-bind.sync를 v-model이 대신한다고 한다. 내용을 읽어보아도 잘 이해가 되지 않아서 다음 stackoverflow를 참고하였다.

 

What is the difference between v-model and .sync when used on a custom component

I don't understand the difference between v-model and .sync used on a component. V-model is a shorthand for binding a variable (myVar) to the component proper...

stackoverflow.com

 

위 글을 정리하자면

1. v-model은 props로 binding하면 props 이름을 무조건 value로만 사용할 수 있다
<->
v-bind.sync는 변수명.sync로 binding하면 변수명으로 props를 변수명으로 사용할 수 있다.

 

2. (1과 이어짐) 따라서 v-bind.sync는 multiple props로 사용할 수 있다.

 

3. v-model은 @update에 값이 갱신되는데 v-bind.sync는 @input에 변경된다(event 이름이 다른데, 이게 큰 영향을 미치는 지는 모르겠다.)

 

※ 'There isn't much difference' 가 두 번째 답변 첫 문장이다.

 

아마 회사에서 실제 개발할 때 사용하는 v-model은 대부분 라이브러리를 사용할 때만 쓰고, custom으로 사용할 때도 v-bind, $emit->@event 스타일로 처리해서 v-model에 대한 이해도는 물론이거니와 v-bind.sync도 잘 몰랐던 것 같다.

 

최종적으로 vue3에서는

v-model:변수명="변수"

형태로 v-model이 v-bind.sync를 merge했다고 하니, 인지만 잘 하고 있으면 되겠다.