Skip to content

Basic Usage

ตัวอย่างการใช้งาน v-model พื้นฐานสำหรับการผูกข้อมูลแบบสองทางกับ input ใน Vue 3 Composition API

vue
<template>
  <div>
    <input v-model="message" placeholder="แก้ไขข้อความ">
    <p>ข้อความ: {{ message }}</p>
  </div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('')
</script>

Value Bindings

การผูกค่ากับ v-model ในรูปแบบต่างๆ เพื่อจัดการกับ input ประเภทต่างๆ ใน Vue 3

Checkbox

การใช้ v-model กับ checkbox เพื่อผูกค่าแบบ boolean

vue
<template>
  <div>
    <input type="checkbox" id="checkbox" v-model="checked">
    <label for="checkbox">{{ checked }}</label>
  </div>
</template>
<script setup>
import { ref } from 'vue'
const checked = ref(false)
</script>

Radio

การใช้ v-model กับ radio buttons เพื่อเลือกค่าจากตัวเลือกที่กำหนด

vue
<template>
  <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>
    <p>เลือก: {{ picked }}</p>
  </div>
</template>
<script setup>
import { ref } from 'vue'
const picked = ref('')
</script>

Select Options

การใช้ v-model กับ select dropdown เพื่อเลือกค่าจากตัวเลือกที่กำหนด

vue
<template>
  <div>
    <select v-model="selected">
      <option disabled value="">กรุณาเลือก</option>
      <option>A</option>
      <option>B</option>
      <option>C</option>
    </select>
    <p>เลือก: {{ selected }}</p>
  </div>
</template>
<script setup>
import { ref } from 'vue'
const selected = ref('')
</script>

Modifiers

ตัวอย่างการใช้ modifier กับ v-model เพื่อปรับแต่งพฤติกรรมการผูกข้อมูลใน Vue 3

.lazy

ใช้เพื่อทำให้การอัพเดทค่าเกิดขึ้นเมื่อเกิด change event แทนที่จะเป็นทุกครั้งที่ input

vue
<template>
  <input v-model.lazy="msg">
</template>
<script setup>
import { ref } from 'vue'
const msg = ref('')
</script>

.number

ใช้เพื่อแปลงค่า input เป็นตัวเลขโดยอัตโนมัติ

vue
<template>
  <input v-model.number="age" type="number">
</template>
<script setup>
import { ref } from 'vue'
const age = ref(0)
</script>

.trim

ใช้เพื่อตัดช่องว่างที่อยู่ด้านหน้าและด้านหลังของข้อความโดยอัตโนมัติ

vue
<template>
  <input v-model.trim="msg">
</template>
<script setup>
import { ref } from 'vue'
const msg = ref('')
</script>

v-model with Component

ตัวอย่างการใช้ v-model กับ custom component เพื่อสร้างการผูกข้อมูลแบบสองทางระหว่าง parent และ child components

vue
<template>
  <custom-input v-model="searchText"></custom-input>
</template>
<script setup>
import { ref } from 'vue'
import CustomInput from './CustomInput.vue'
const searchText = ref('')
</script>

Released under the MIT License