前端学习-vue学习004-表单绑定
同时使用 v-bind 和 v-on 来在表单的输入元素上创建双向绑定:
<input :value="text" @input="onInput">
在文本框里输入,同时更新
里的文本。实现如下
<script setup>
import { ref } from 'vue'
const text = ref('')
function onInput(e) {
text.value = e.target.value
}
</script>
<template>
<input :value="text" @input="onInput" placeholder="Type here">
<p>{{ text }}</p>
</template>
使用语法糖 v-model 指令,上述操作可简化为
<input v-model="text">
v-model 会将被绑定的值与 的值自动同步,这样我们就不必再使用事件处理函数了。
v-model 不仅支持文本输入框,也支持诸如多选框、单选框、下拉框之类的输入类型
修改后的实现如下
<script setup>
import { ref } from 'vue'
const text = ref('')
// function onInput(e) {
// text.value = e.target.value
// }
</script>
<template>
<input v-model="text" placeholder="Type here">
<p>{{ text }}</p>
</template>

浙公网安备 33010602011771号