表单输入与绑定

v-model 使用

输入框

复选框

<script setup lang="ts">
import {ref,reactive} from 'vue';
const text = ref(false)
</script>

<template>
<div>
  <p>isPressed: {{text}}</p>
<input type="checkbox" v-model="text">

</div>
</template>

image-20250122213149791

复选框

<script setup lang="ts">
import {ref,reactive} from 'vue';
const checkedNames = ref([])
</script>

<template>
<div>
<div>Checked names: {{ checkedNames }}</div>

<input type="checkbox"  value="Jack" v-model="checkedNames" />
<label for="jack">Jack</label>

<input type="checkbox" value="John" v-model="checkedNames" />
<label for="john">John</label>

</div>
</template>

image-20250122213409343

单选按钮

<script setup lang="ts">
import {ref,reactive} from 'vue';
const picked = ref()
</script>

<template>
<div>
<div>Picked: {{ picked }}</div>

<input type="radio" id="one" value="One" v-model="picked" />
<label for="one">One</label>

<input type="radio" id="two" value="Two" v-model="picked" />
<label for="two">Two</label>
</div>
</template>

image-20250122213506986

选择器

<script setup lang="ts">
import {ref,reactive} from 'vue';
const selected = ref()
</script>

<template>
<div>
  <div>selected: {{selected}}</div>
  <select v-model="selected" >
    <option disabled>Please select one</option>
    <option selected>A</option>
    <option>B</option>
    <option>C</option>
    <option>D</option>
  </select>
</div>
</template>

image-20250122213839446

使用 v-for 动态渲染

<script setup lang="ts">
import {ref,reactive} from 'vue';
const selected = ref()

const options = ref([
{
  text: "A.猫",
  value: "A"
},
{
  text: "B.狗",
  value: "B"
},
{
  text: "C.老鼠",
  value: "C"
}
])
</script>

<template>
<div>
  <div>selected: {{selected}}</div>
  <select v-model="selected" >
    <option v-for="option in options" :value="option.value">{{option.text}}</option>
  </select>

</div>
</template>

image-20250122214512853

<script setup lang="ts">
import { ref } from 'vue';

// 当前选中的值
const selected = ref('');

// 选项列表
const options = ref([
  {
    id: 1,
    text: 'A.猫',
    value: 'A',
  },
  {
    id: 2,
    text: 'B.狗',
    value: 'B',
  },
  {
    id: 3,
    text: 'C.老鼠',
    value: 'C',
  },
]);
</script>

<template>
  <div>
    <div>selected: {{ selected }}</div>
    <div v-for="option in options" :key="option.id">
      <!-- 绑定 input 的 id 和 value -->
      <input
        type="radio"
        :id="`option-${option.id}`"
        :value="option.value"
        v-model="selected"
      />
      <!-- 绑定 label 的 for -->
      <label :for="`option-${option.id}`">{{ option.text }}</label>
    </div>
  </div>
</template>

image-20250122214937369

修饰符