Đăng nhập

BÀI 6: PROPS, SLOTS & DEFINEPAGEMETA TRONG NUXT

Cùng tiếp tục với Bài 6 – Props, Slots và definePageMeta trong NuxtJS. Đây là các khái niệm giúp bạn tạo component linh hoạt, truyền dữ liệu giữa chúng, và tối ưu SEO cho từng trang.


1. Truyền props vào component

Ví dụ: Tạo components/Button.vue

<template>
  <button :style="{ backgroundColor: color }">
    {{ label }}
  </button>
</template>

<script setup>
defineProps({
  label: String,
  color: {
    type: String,
    default: '#42b983'
  }
})
</script>

Dùng trong pages/index.vue

<template>
  <Button label="Click Me" color="#ff6600" />
</template>

<script setup>
import Button from '~/components/Button.vue'
</script>

2. Sử dụng slots để tùy biến nội dung

Ví dụ: Tạo components/Card.vue

<template>
  <div class="card">
    <slot />
  </div>
</template>

<style scoped>
.card {
  padding: 16px;
  border: 1px solid #ccc;
  border-radius: 8px;
}
</style>

Dùng trong pages/index.vue

<template>
  <Card>
    <h2>Xin chào</h2>
    <p>Đây là nội dung bên trong card.</p>
  </Card>
</template>

<script setup>
import Card from '~/components/Card.vue'
</script>

3. Slot đặt tên – named slots

Sửa Card.vue:

<template>
  <div class="card">
    <header><slot name="header" /></header>
    <main><slot /></main>
    <footer><slot name="footer" /></footer>
  </div>
</template>

Dùng như sau:

<Card>
  <template #header>
    <h3>Tiêu đề</h3>
  </template>

  <p>Nội dung chính</p>

  <template #footer>
    <small>© 2025</small>
  </template>
</Card>

4. definePageMeta – cấu hình SEO và layout trang

Trong pages/about.vue:

<script setup>
definePageMeta({
  title: 'Giới thiệu - Công ty ABC',
  layout: 'default'
})
</script>

<template>
  <h1>Giới thiệu</h1>
</template>
  • title: tự động đổ vào <head><title>...</title>
  • layout: chỉ định layout cụ thể cho trang

5. Thêm meta tag SEO

<script setup>
definePageMeta({
  title: 'Trang Blog - Vue App',
  meta: [
    { name: 'description', content: 'Tổng hợp kiến thức VueJS dễ hiểu' },
    { property: 'og:title', content: 'Trang Blog Vue' }
  ]
})
</script>

Bạn đã học được

  • Truyền dữ liệu bằng props
  • Tùy biến nội dung component với slot
  • Tạo slot đặt tên (header/footer)
  • Sử dụng definePageMeta để cấu hình SEO và layout

Bài tập mở rộng

  1. Tạo component Banner.vue nhận props: title, subtitle
  2. Tạo component LayoutAdmin.vue dùng slot tên: header, content, footer
  3. Trang /contact.vue dùng definePageMeta để đặt title và description phù hợp

Thảo luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Đăng ký nhận tin mới

Nhận bài học, tài nguyên và cơ hội việc làm qua email hàng tuần.

Chúng tôi cam kết không spam. Bạn có thể hủy bất cứ lúc nào.