คู่มือการใช้งาน Vue.js
อินสแตนซ์ของแอปพลิเคชัน (Application Instance)
ทุกแอปพลิเคชัน Vue เริ่มต้นด้วยการสร้างอินสแตนซ์ของแอปพลิเคชันใหม่ด้วยฟังก์ชัน createApp:
import { createApp } from 'vue'
const app = createApp({
/* root component options */
})
คอมโพเนนต์ราก (Root Component)
ออบเจ็กต์ที่ส่งเข้าไปใน createApp ถือเป็นคอมโพเนนต์ ทุกแอปต้องมี "คอมโพเนนต์ราก" ซึ่งสามารถบรรจุคอมโพเนนต์อื่นๆ เป็นลูกได้
การเมานต์แอป (Mounting the App)
อินสแตนซ์ของแอปพลิเคชันจะไม่เรนเดอร์อะไรเลยจนกว่าจะเรียกเมธอด .mount():
app.mount('#app')
การกำหนดค่าแอป (App Configurations)
อินสแตนซ์ของแอปพลิเคชันเปิดเผยออบเจ็กต์ .config สำหรับการกำหนดค่าในระดับแอป:
// App-level error handler
app.config.errorHandler = (err) => {
/* handle error */
}
// Register global component
app.component('TodoDeleteButton', TodoDeleteButton)
อินสแตนซ์ของแอปพลิเคชันหลายตัว (Multiple Application Instances)
คุณสามารถสร้างแอปพลิเคชัน Vue หลายตัวบนหน้าเว็บเดียวกันได้:
const app1 = createApp({ /* ... */ })
app1.mount('#container-1')
const app2 = createApp({ /* ... */ })
app2.mount('#container-2')
ไวยากรณ์เทมเพลต (Template Syntax)
Vue ใช้ไวยากรณ์เทมเพลตที่อิงกับ HTML ซึ่งช่วยให้คุณผูก DOM ที่เรนเดอร์แล้วเข้ากับข้อมูลของอินสแตนซ์คอมโพเนนต์ได้อย่างเป็นแบบประกาศ
การแทรกข้อความ (Text Interpolation)
รูปแบบพื้นฐานที่สุดของการผูกข้อมูล (data binding) ใช้ไวยากรณ์ "Mustache" (วงเล็บปีกกาคู่):
<span>Message: {{ msg }}</span>
HTML ดิบ (Raw HTML)
ใช้คำสั่ง (directive) v-html เพื่อแสดงผล HTML จริง:
<p v-html="rawHtml"></p>
คำเตือนด้านความปลอดภัย: การเรนเดอร์ HTML ใดๆ แบบไดนามิกอาจนำไปสู่ช่องโหว่ XSS ใช้ v-html เฉพาะกับเนื้อหาที่เชื่อถือได้เท่านั้น และห้ามใช้กับเนื้อหาที่ผู้ใช้จัดหาให้เด็ดขาด
การผูกแอตทริบิวต์ (Attribute Bindings)
ใช้คำสั่ง v-bind เพื่อผูกแอตทริบิวต์ HTML:
<!-- Full syntax -->
<div v-bind:id="dynamicId"></div>
<!-- Shorthand -->
<div :id="dynamicId"></div>
<!-- Same-name shorthand (Vue 3.4+) -->
<div :id></div>
แอตทริบิวต์แบบบูลีน (Boolean Attributes)
แอตทริบิวต์แบบบูลีนจะถูกใส่เข้าไปเมื่อค่าที่ผูกไว้เป็นค่า truthy:
<button :disabled="isButtonDisabled">Button</button>
การผูกหลายแอตทริบิวต์แบบไดนามิก (Dynamically Binding Multiple Attributes)
ผูกหลายแอตทริบิวต์จากออบเจ็กต์โดยใช้ v-bind โดยไม่มีอาร์กิวเมนต์:
const objectOfAttrs = {
id: 'container',
class: 'wrapper'
}
<div v-bind="objectOfAttrs"></div>
นิพจน์ JavaScript (JavaScript Expressions)
Vue รองรับนิพจน์ JavaScript แบบเต็มรูปแบบในทุกการผูกข้อมูล (data binding):
{{ number + 1 }}
{{ ok ? 'YES' : 'NO' }}
{{ message.split('').reverse().join('') }}
<div :id="`list-${id}`"></div>
การเรียกใช้ฟังก์ชัน (Calling Functions)
เรียกเมธอดที่คอมโพเนนต์เปิดเผยในนิพจน์การผูกข้อมูล:
<time :title="toTitleDate(date)" :datetime="date">
{{ formatDate(date) }}
</time>
การเข้าถึงตัวแปรโกลบอลแบบจำกัด (Restricted Globals Access)
นิพจน์ในเทมเพลตสามารถเข้าถึงรายการตัวแปรโกลบอลที่จำกัดเท่านั้น (Math, Date เป็นต้น) เพิ่มตัวแปรโกลบอลเพิ่มเติมได้ผ่าน app.config.globalProperties
คำสั่ง (Directives)
คำสั่ง (Directives) เป็นแอตทริบิวต์พิเศษที่มีคำนำหน้า v-
อาร์กิวเมนต์ (Arguments)
คำสั่งบางตัวรับอาร์กิวเมนต์ โดยระบุด้วยเครื่องหมายโคลอน:
<!-- v-bind argument -->
<a v-bind:href="url"> ... </a>
<a :href="url"> ... </a>
<!-- v-on argument -->
<a v-on:click="doSomething"> ... </a>
<a @click="doSomething"> ... </a>
อาร์กิวเมนต์แบบไดนามิก (Dynamic Arguments)
ใช้นิพจน์ JavaScript ในอาร์กิวเมนต์ของคำสั่งด้วยเครื่องหมายวงเล็บเหลี่ยม:
<a :[attributeName]="url"> ... </a>
<a @[eventName]="doSomething"> ... </a>
ข้อจำกัด:
- อาร์กิวเมนต์แบบไดนามิกต้องมีค่าที่ประเมินออกมาเป็นสตริงหรือ null
- หลีกเลี่ยงนิพจน์ที่ซับซ้อน ให้ใช้ computed properties แทน
- ในเทมเพลต DOM ให้หลีกเลี่ยงตัวอักษรพิมพ์ใหญ่ในคีย์แบบไดนามิก
ตัวปรับแต่ง (Modifiers)
ตัวปรับแต่ง (Modifiers) เป็นส่วนต่อท้ายพิเศษที่ระบุด้วยเครื่องหมายจุด:
<form @submit.prevent="onSubmit">...</form>
พื้นฐานของ Reactivity
การประกาศสถานะแบบ Reactive (Declaring Reactive State)
สร้างตัวอ้างอิงแบบ reactive ด้วย ref():
import { ref } from 'vue'
const count = ref(0)
console.log(count.value) // 0
count.value++
console.log(count.value) // 1
ออบเจ็กต์แบบ Reactive (Reactive Objects)
สร้างออบเจ็กต์แบบ reactive ด้วย reactive():
import { reactive } from 'vue'
const state = reactive({
count: 0
})
Computed Properties
สร้าง computed properties ด้วย computed():
import { ref, computed } from 'vue'
const author = ref({
name: 'John Doe',
books: [
'Vue 2 Guide',
'Vue 3 Guide',
'Vue Mastery'
]
})
const publishedBooksMessage = computed(() => {
return author.value.books.length > 0
? 'Yes'
: 'No'
})
Watchers
เฝ้าดูการเปลี่ยนแปลงข้อมูลแบบ reactive ด้วย watch():
import { ref, watch } from 'vue'
const question = ref('')
const answer = ref('Questions usually contain a question mark. ;-)')
// Watch single ref
watch(question, async (newQuestion, oldQuestion) => {
if (newQuestion.indexOf('?') > -1) {
answer.value = 'Thinking...'
try {
const res = await fetch('https://yesno.wtf/api')
answer.value = (await res.json()).answer
} catch (error) {
answer.value = 'Error! Could not reach the API. ' + error
}
}
})
พื้นฐานของคอมโพเนนต์ (Component Basics)
การกำหนดคอมโพเนนต์ (Defining Components)
// Define component
const Component = {
data() {
return {
count: 0
}
},
template: `<button @click="count++">Count is: {{ count }}</button>`
}
การส่ง Props (Passing Props)
// Child component
const Child = {
props: ['msg'],
template: `<div>{{ msg }}</div>`
}
// Parent component
const Parent = {
components: { Child },
template: `<Child msg="Hello!"></Child>`
}
การส่งเหตุการณ์ (Emitting Events)
// Child component
const Child = {
emits: ['response'],
methods: {
respond() {
this.$emit('response', 'Hello from child!')
}
},
template: `<button @click="respond">Respond</button>`
}
สล็อต (Slots)
<!-- Child component -->
<template>
<div>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
<!-- Parent component -->
<Child>
<p>This is default slot content</p>
<template #footer>
<p>This is footer slot content</p>
</template>
</Child>
