Basic Vue Components
Define components
การสร้างคอมโพเนนต์พื้นฐานใน Vue
vue
<script setup>
// ประกาศคอมโพเนนต์แบบ Composition API
const MyComponent = {
template: '<div>นี่คือคอมโพเนนต์ของฉัน</div>'
}
</script>
<template>
<MyComponent />
</template>
Using components
การใช้งานคอมโพเนนต์ที่สร้างขึ้น
vue
<script setup>
import MyComponent from './MyComponent.vue'
</script>
<template>
<MyComponent />
</template>
Props
การส่งข้อมูลจาก Parent ไปยัง Child component
vue
<script setup>
const props = defineProps({
message: String
})
</script>
<template>
<div>{{ message }}</div>
</template>
Events
การส่ง Event จาก Child ไปยัง Parent component
vue
<script setup>
const emit = defineEmits(['update'])
function handleClick() {
emit('update', 'ข้อมูลที่อัปเดต')
}
</script>
<template>
<button @click="handleClick">อัปเดต</button>
</template>
Slot
การใช้ Slot เพื่อกำหนดเนื้อหาที่สามารถแทรกได้
vue
<template>
<div>
<slot>เนื้อหาเริ่มต้น</slot>
</div>
</template>
Dynamic components
การสร้างคอมโพเนนต์แบบไดนามิก
vue
<script setup>
import { ref } from 'vue'
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'
const currentComponent = ref(ComponentA)
</script>
<template>
<component :is="currentComponent" />
</template>
Async components
การโหลดคอมโพเนนต์แบบ Asynchronous
vue
<script setup>
import { defineAsyncComponent } from 'vue'
const AsyncComponent = defineAsyncComponent(() =>
import('./AsyncComponent.vue')
)
</script>
<template>
<AsyncComponent />
</template>
Advanced Vue Components
Registration
การลงทะเบียนคอมโพเนนต์แบบ Global
javascript
import { createApp } from 'vue'
import App from './App.vue'
import GlobalComponent from './GlobalComponent.vue'
const app = createApp(App)
app.component('GlobalComponent', GlobalComponent)
app.mount('#app')
Fallthrough attributes
การส่งผ่าน Attributes ที่ไม่ได้ระบุใน Props
vue
<script setup>
const props = defineProps(['title'])
</script>
<template>
<div v-bind="$attrs">
<h1>{{ title }}</h1>
</div>
</template>
Provide/Inject
การส่งข้อมูลข้ามหลายระดับของคอมโพเนนต์
vue
<!-- Parent Component -->
<script setup>
import { provide } from 'vue'
provide('message', 'ข้อความจาก Parent')
</script>
<!-- Child Component -->
<script setup>
import { inject } from 'vue'
const message = inject('message')
</script>
<template>
<div>{{ message }}</div>
</template>