양방향 데이터 바인딩
: vue 데이터 변경시 화면단의 요소가 변경되고, 화면단의 요소 변경 시 vue 데이터가 변경된다.
v-bind
로 vue 데이터 변경시 화면단의 요소가 변경하고v-on
으로 화면단의 요소 변경 시 vue 데이터를 변경한다. <div id="app">
<p>{{ inputText1 }}</p>
<input :value="inputText1" @input="onInput">
</div>
const app = createApp({
setup() {
const inputText1 = ref('안녕')
const onInput = function (event) {
inputText1.value = event.currentTarget.value
//inputText1.value = event.target.value;
}
return {
inputText1,
onInput,
}
}
})
<div id="app">
<p>{{ inputText2 }}</p>
<input v-model="inputText2"/>
</div>
const app = createApp({
setup() {
const inputText2 = ref('안녕')
const onInput = function (event) {
// inputText1.value = event.currentTarget.value
inputText1.value = event.target.value;
}
return {
onInput,
inputText2,
}
}
})
한글을 입력받는 경우에 정확히 양방향 바인딩을 하려면 v-bind 와 v-on을 함께 쓰는 방법을 선택해야 한다.
v-model을 사용하여 한글 입력을 받으면 하나의 글자가 완성 된후 포커스가 옮겨지기 때문에 정확한 바인딩이 안된다.
<input type="checkbox" id="checkbox" v-model="checked">
<label for="checkbox">{{ checked }}</label>
const checked = ref(false)
return {
checked,
}
<div>Checked names: {{ checkedNames }}</div>
<input type="checkbox" id="alice" value="Alice" v-model="checkedNames">
<label for="alice">Alice</label>
<input type="checkbox" id="bella" value="Bella" v-model="checkedNames">
<label for="bella">Bella</label>
const checkedNames = ref([])
return {
checkedNames,
}
<div>Selected: {{ selected }}</div>
<select v-model="selected">
<option disabled value="">Please select one</option>
<option>Alice</option>
<option>Bella</option>
<option>Cathy</option>
</select>
const selected = ref('')