---
title: "用 Vue.js 实现简单的 Flux 架构"
description: "对于只需要简单状态管理模式的小型 app，我总是用一个组件来保存整个 app 的状态，也就是一个 container。它作为 single source of truth，让 app 引用自己的状态…"
canonical: https://oozou.com/til/simple-flux-architecture-with-vue-js-50
locale: zh-Hans
date: 2020-10-13
topic: javascript
---

# 用 Vue.js 实现简单的 Flux 架构

> 对于只需要简单状态管理模式的小型 app，我总是用一个组件来保存整个 app 的状态，也就是一个 container。它作为 single source of truth，让 app 引用自己的状态…

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

对于只需要简单状态管理模式的小型 app，我总是用一个组件来保存整个 app 的状态，也就是一个 container。它作为 single source of truth，让 app 引用自己的状态。Vue 提供了一种在根层级创建全局事件监听器的机制，叫做 *EventBus*，这是模拟 flux 架构超级简单的方式。

你只需要一个把 Vue 导出为 *EventBus* 的模块，像这样

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

接着你就可以在 container 里用它来*监听*来自 app 中任何组件的事件。我通常会在 *created* 生命周期加上监听器。

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

接着你可以在任何组件中导入 *EventBus*，就能从任何地方触发 *my-custom-event*，不必把事件 *emit* 给该组件的父组件，也不必在触发变更的组件和目标 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/zh-Hans/contact

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