[Vue.js] สร้าง Custom Input Component

NottDev
2 min readOct 6, 2021

--

เมื่อเราต้องการสร้าง Input component ขึ้นมาใช้งานเอง แบบที่เราต้องการ เพื่อให้สามารถนำไปใช้งานได้ง่ายขึ้น ซึ่งบทความนี้จะมาแนะนำการสร้าง Custom input component ใน Vue.js โดยมีวิธีการอย่างไร ไปดูกันเลยครับ ++

ก่อนอื่นขออธิบายเกี่ยวกับการใช้งาน v-model บน Input element ใน vue.js

<input v-model="username" placeholder="Username" />

การใช้งานก็ง่ายนิดเดียวเพียงแค่เพิ่ม v-model attribute ใน input element ก็สามารถสร้าง two way binding ของ input ได้แล้ว ซึ่งค่า value จะถูกเก็บไว้ที่ตัวแปร username โดยการทำงานของ v-model นั้นจะแยกออกเป็น 2 ส่วน คือ

  1. value property คือ เก็บค่าของ input
  2. input event คือ ฟังก์ชั่นเมื่อมีเหตุการณ์กับ input

สามารถเขียนแยกการทำงานของ v-model ได้ออกมาแบบนี้

<input 
placeholder="Username"
:value="username"
@input="username = $event.target.value"
/>

สรุป v-model คือ attribute สำหรับสร้าง two way binding บน input, textarea และ select elements โดยจะมีการ update และเก็บค่า แบบอัติโนมัติ ให้ตามประเภทของ element นั้นๆ ได้อย่างถูกต้อง

อธิบายมาพอสังเขปแล้ว ต่อไปมาเขียน Custom Input Component กันดีกว่า..

สำหรับ Vue เวอร์ชั่น 2

โค้ด Custom Input Component สำหรับ Vue เวอร์ชั่น 2

สำหรับ Vue เวอร์ชั่น 2 v-model จะแยกเป็น prop ชื่อ value และ event ชื่อ input

สำหรับ Vue เวอร์ชั่น 3

โค้ด Custom Input Component สำหรับ Vue เวอร์ชั่น 3

สำหรับ Vue เวอร์ชั่น 3 v-model จะแยกเป็น prop ชื่อ modelValue และ event ชื่อ update:modelValue

วิธีใช้งาน Component

// โหลด Component มาใช้
import CustomInput from '~/components/CustomInput.vue'
export default {
components: { CustomInput },
...
}// เรียกใช้งาน Component
<custom-input
id="username"
v-model="username"
label="Username"
placeholder="Type your username"
autocomplete="off"
/>

สำหรับในส่วนของการใช้งาน ก็เริ่มจาก import component เข้ามาใช้ แล้วสามารถใช้งาน component เหมือนที่ใช้งาน input tag ปกติได้เลยครับ โดยในโค้ดตัวอย่างเป็นการสร้างเพื่อเป็น idea หากต้องการใช้งาน attribute ส่วนไหนเพิ่มเติม สามารถเพิ่มรายละเอียดใน Custom component ได้ตามต้องการเลยครับ

สุดท้ายนี้ก็หวังว่าบทความนี้จะเป็นประโยชน์กับเพื่อนๆ ไม่มากก็น้อย เกี่ยวกับการสร้าง Custom Input Component ใน Vue.js

Reference

Your only limit is your mind & Enjoy coding

--

--

NottDev
NottDev

Written by NottDev

Your only limit is your mind.

No responses yet