Cách định nghĩa component và sử dụng các directive phổ biến trong Vue 3

Trong Vue 3, bạn có thể khai báo component thông qua hàm defineComponent để tận dụng hỗ trợ kiểu và IntelliSense tốt hơn.

import { defineComponent } from 'vue';

export default defineComponent({
  name: 'AlertBox',
  props: {
    content: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const triggerAlert = () => {
      window.alert(props.content);
    };

    return {
      triggerAlert
    };
  },
  template: `
    <div class="alert-container">
      <span>{{ content }}</span>
      <button @click="triggerAlert">Báo động!</button>
    </div>
  `
});

Ở ví dụ trên, component AlertBox nhận vào prop content và cung cấp một hàm triggerAlert để hiển thị hộp thoại cảnh báo. Template kết nối sự kiện click với hàm này và hiển thị nội dung prop.

Để đăng ký và sử dụng component này trong ứng dụng chính:

import { createApp } from 'vue';
import AlertBox from './components/AlertBox.vue';

const rootApp = createApp({});

rootApp.component('alert-box', AlertBox);
rootApp.mount('#app-root');

Vue 3 duy trì hầu hết các directive quen thuộc từ Vue 2, đồng thời cải tiến cú pháp và hiệu năng. Dưới đây là cách sử dụng các directive phổ biến:

<template>
  <section>
    <!-- Ràng buộc hai chiều -->
    <input v-model="userInput" placeholder="Nhập nội dung..." />

    <!-- Hiển thị/ẩn theo điều kiện -->
    <p v-show="isVisible">Nội dung có thể ẩn hiện</p>

    <!-- Chèn HTML động -->
    <div v-html="dynamicHtml"></div>

    <!-- Chỉ render một lần -->
    <h3 v-once>{{ staticTitle }}</h3>

    <!-- Ràng buộc thuộc tính động -->
    <div 
      :class="{ highlight: isHighlighted }"
      :style="{ backgroundColor: bgColor }"
    >
      Kiểu dáng động
    </div>

    <!-- Lặp danh sách với key -->
    <ul>
      <li v-for="product in products" :key="product.sku">
        {{ product.label }}
      </li>
    </ul>
  </section>
</template>

<script>
export default {
  data() {
    return {
      userInput: '',
      isVisible: true,
      dynamicHtml: '<em>Chữ nghiêng từ HTML động</em>',
      staticTitle: 'Tiêu đề không đổi',
      isHighlighted: true,
      bgColor: '#f0f8ff',
      products: [
        { sku: 'A001', label: 'Sản phẩm Alpha' },
        { sku: 'B002', label: 'Sản phẩm Beta' },
        { sku: 'C003', label: 'Sản phẩm Gamma' }
      ]
    };
  }
};
</script>

Các directive như v-model, v-show, v-html, v-once, :class, :stylev-for giúp bạn xây dựng giao diện linh hoạt và phản hồi nhanh chóng với dữ liệu.

Thẻ: Vue3 definecomponent directive vue-directives composition-api

Đăng vào ngày 22 tháng 6 lúc 21:07