Tận dụng khả năng giao tiếp giữa các component trong ứng dụng Vue.js là một phần quan trọng của việc xây dựng giao diện người dùng linh hoạt và dễ bảo trì. Emitting và Listening to Events là một trong những cách mạnh mẽ nhất để làm điều này.

Trong Vue.js, bạn có thể sử dụng mô hình "Emitting and Listening to Events" để truyền dữ liệu và tương tác giữa các component khác nhau một cách dễ dàng và linh hoạt. Với cách tiếp cận này, một component có thể phát ra (emit) một sự kiện khi một hành động xảy ra và các component khác có thể lắng nghe (listen) và xử lý sự kiện đó.

Khi một component phát ra một sự kiện, các component khác có thể lắng nghe sự kiện đó và phản ứng tương ứng. Việc này tạo ra một cách liên kết mạnh mẽ giữa các component, cho phép chúng tương tác với nhau một cách linh hoạt và dễ dàng bảo trì.

Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách sử dụng $emit để phát ra sự kiện từ một component và sử dụng directive v-on để lắng nghe và xử lý sự kiện đó trong các component khác. Chúng ta cũng sẽ xem xét các kỹ thuật phổ biến để truyền dữ liệu qua sự kiện, tạo ra một cơ chế mạnh mẽ để xây dựng các ứng dụng Vue.js phức tạp.

Dưới đây là một ví dụ minh họa về cách phát ra (emit) và lắng nghe sự kiện trong Vue.js:

<!-- ChildComponent.vue -->

<template>
  <section>
    <li>
      <h2>{{ name }} - {{ isFavorite ? "Fa" : "" }}</h2>
      <button @click="toggleFavorite">Show Favorite</button>
      <button @click="toggleDetails">Show Details</button>
      <ul v-if="detailsAreVisible">
        <li>
          <strong>Phone:</strong>
          {{ phoneNumber }}
        </li>
        <li>
          <strong>Email:</strong>
          {{ email }}
        </li>
      </ul>
      <button @click="deleteFriend">Delete</button>
    </li>
  </section>
</template>
  
<script>
export default {
  emits: ['toggle-favorite', 'delete-friend'],
  props: {
    id:{
      type: String,
      required: true
    },
    name: {
      type: String,
      required: true,
    },
    email: {
      type: String,
      required: true,
    },
    phoneNumber: {
      type: String,
      required: true,
    },
    isFavorite: {
      type: Boolean,
      required: false,
    },
  },
  data() {
    return {
      detailsAreVisible: false,
    };
  },
  methods: {
    toggleDetails() {
      this.detailsAreVisible = !this.detailsAreVisible;
    },
    toggleFavorite () {
      this.$emit('toggle-favorite', this.id)
    },
    deleteFriend() {
      this.$emit('delete-friend', this.id)
    }
  },
};
</script>

Trong ví dụ trên, ChildComponent có một button Delete khi được click, nó sẽ phát ra sự kiện có tên là 'delete-friend' và truyền một id sang component cha.

<button @click="$emit('delete-friend', id)">Delete</button>

Và ở component cha nó sẽ lắng nghe bằng cách như sau:

<!-- ParentComponent.vue -->

<template>
  <section>
    <header>
      <h1>My Friends</h1>
    </header>
    <add-friend @add-friend="addFriend"></add-friend>
<ul>
  <friend-list
    v-for="friend in friends"
    :key="friend.id"
    :id="friend.id"
    :name="friend.name"
    :phone-number="friend.phone"
    :email="friend.email"
    :is-favorite="friend.isFavorite"
    @toggle-favorite="updateFavorite"
    @delete-friend="deleteFriend"
  >
  </friend-list>
</ul>
  </section>
</template>

<script>

export default {
  data() {
    return {
      friends: [
        {
          id: "1",
          name: "Manuel Lorenz",
          phone: "0123 45678 90",
          email: "manuel@localhost.com",
          isFavorite: true,
        },
        {
          id: "2",
          name: "Julie Jones",
          phone: "0987 654421 21",
          email: "julie@localhost.com",
          isFavorite: false,
        },
      ],
    };
  },
  methods: {
    updateFavorite(friendId) {
     const idFriend = this.friends.find((friend) => friend.id === friendId);
     idFriend.isFavorite = !idFriend.isFavorite
    },
    addFriend(name, email, phone) {
      this.friends.push({
        id: new Date().toISOString(),
        name: name,
        phone: phone,
        email: email,
        isFavorite: false,
      })
    },
    deleteFriend(friendId) {
      this.friends = this.friends.filter(friend => friend.id !== friendId);
    }
  }
};
</script>

Trong ví dụ này, ParentComponent lắng nghe sự kiện 'delete-friend' từ ChildComponent. Khi sự kiện được phát ra từ ChildComponent, phương thức deleteFriend trong ParentComponent được gọi và dữ liệu được truyền từ ChildComponent được sử dụng để delete.

<friend-list
  ...
  @delete-friend="deleteFriend"
>
</friend-list>
  • @delete-friend: Tên emit mà chúng ta đã đặt bên ChildComponent
  • deleteFriend: Là phương thức để xử lý deleteFriend qua emit
export default {
  methods: {
    deleteFriend(friendId) {
      this.friends = this.friends.filter(friend => friend.id !== friendId);
    }
  }
};

Defining & Validating Custom Events

Để định nghĩa và xác nhận sự kiện tùy chỉnh trong Vue.js, bạn có thể sử dụng option emits trong định nghĩa của coponent. Tùy chọn này cho phép bạn liệt kê các sự kiện mà component có thể phát ra, cũng như xác định các loại dữ liệu mà mỗi sự kiện có thể truyền đi.

Ví dụ: Liệt kê các sự kiện.

export default {
  emits: ['toggle-favorite', 'delete-friend'],
  ...
};

Ví dụ: Xác định các loại dữ liệu mà mỗi sự kiện có thể truyền đi.

export default {
  emits: {
    'delete-friend': function (id) {
      if (id) {
        return true;
      } else {
        console.log("id is missing");
        return false;
      }
    }
  },
}

Trong Vue.js, tùy chọn emits không bắt buộc. Điều này có nghĩa là nếu bạn không cung cấp tùy chọn emits trong định nghĩa của một component, component đó vẫn có thể phát ra các sự kiện tùy chỉnh bình thường bằng cách sử dụng phương thức $emit. Tuy nhiên, khi bạn sử dụng emits, Vue.js sẽ kiểm tra xác thực và cảnh báo nếu có lỗi trong quá trình phát ra sự kiện.

Việc sử dụng tùy chọn emits là một cách tốt để làm cho mã của bạn dễ bảo trì hơn và giảm thiểu lỗi liên quan đến việc truyền dữ liệu qua sự kiện. Bằng cách xác định các sự kiện mà component có thể phát ra cùng với kiểu dữ liệu của mỗi sự kiện, bạn giúp đảm bảo rằng sự tương tác giữa các component diễn ra một cách dễ dàng và nhất quán hơn.

 

Bình luận (0)

Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Michael Gough
Learning English Everyday