VUE基础-表单绑定

我们同时使用v-bind 和 v-on 来在表单的输入元素上创建双向绑定:
完整示例如下:

<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>

为了简化双向绑定,Vue 提供了一个 v-model 指令,它实际上是上述操作的语法糖:

<input v-model="text">

v-model 会将被绑定的值与 <input> 的值自动同步,这样我们就不必再使用事件处理函数了。

v-model 不仅支持文本输入框,也支持诸如多选框、单选框、下拉框之类的输入类型。

使用v-model重构后的代码为:

<script setup>
import { ref } from 'vue'

const text = ref('')

</script>

<template>
  <input v-model="text" placeholder="Type here">
  <p>{{ text }}</p>
</template>
posted @ 2023-07-11 14:28  客舍青  阅读(42)  评论(0)    收藏  举报