---
title: "Flux Architecture แบบง่ายด้วย Vue.js"
description: "สำหรับแอปเล็ก ๆ ที่ต้องการแค่ pattern จัดการ state แบบง่าย ๆ ผู้เขียนมักใช้ component เดียวเก็บ state ของแอปไว้ เรียกว่า container ซึ่งทำหน้าที่เป็น single source of truth ให้แอปใช้อ้างอิง..."
canonical: https://oozou.com/til/simple-flux-architecture-with-vue-js-50
locale: th
date: 2020-10-13
topic: javascript
---

# Flux Architecture แบบง่ายด้วย Vue.js

> สำหรับแอปเล็ก ๆ ที่ต้องการแค่ pattern จัดการ state แบบง่าย ๆ ผู้เขียนมักใช้ component เดียวเก็บ state ของแอปไว้ เรียกว่า container ซึ่งทำหน้าที่เป็น single source of truth ให้แอปใช้อ้างอิง...

Published: 2020-10-13 · Topic: [javascript](https://oozou.com/th/til-topics/javascript) ([markdown](https://oozou.com/th/til-topics/javascript.md))

สำหรับแอปเล็ก ๆ ที่ต้องการแค่ pattern จัดการ state แบบง่าย ๆ ผู้เขียนมักใช้ component เดียวเก็บ state ของแอปไว้ เรียกว่า container ซึ่งทำหน้าที่เป็น single source of truth ให้แอปใช้อ้างอิง state ของตัวเอง Vue มีกลไกสำหรับสร้าง global event listener ที่ระดับ root เรียกว่า *EventBus* ซึ่งเป็นวิธีสุดง่ายในการเลียนแบบ Flux Architecture

ทั้งหมดที่คุณต้องมีคือ module เดียวที่ export Vue เป็น *EventBus* แบบนี้

```javascript
// EventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
```

จากนั้นใช้ *EventBus* ใน container เพื่อ *listen* event จาก component ไหนก็ได้ในแอป ปกติผู้เขียนจะเพิ่ม listener ไว้ใน life cycle *created*

```javascript
EventBus.$on('event-name', callback)
```

จากนั้น import *EventBus* เข้าไปใน component ไหนก็ได้ แล้ว trigger *my-custom-event* จากตรงไหนก็ได้ ไม่ต้อง *emit* event ขึ้นไปหา parent แล้วทำซ้ำแบบเดิมในทุก component ที่คั่นอยู่ระหว่าง component ต้นทางกับ container ปลายทาง

```javascript
// Goes directly to the global listener and triggers callback
EventBus.$emit('event-name')
```

แค่นั้นเลย ถ้ามันเริ่มซับซ้อนเกินไป ลองพิจารณาใช้ Vuex

---

Contact OOZOU: hello@oozou.com · +66 2544 0000 · https://oozou.com/th/contact

More for AI agents: https://oozou.com/llms.txt · every page has a markdown twin at its URL plus ".md"
