Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit e6e280d

Browse filesBrowse files
committed
✨ Vue2 组件通信与事件处理最佳实践
1 parent 9ecf176 commit e6e280d
Copy full SHA for e6e280d

File tree

Expand file treeCollapse file tree

16 files changed

+263
-1121
lines changed
Filter options
Expand file treeCollapse file tree

16 files changed

+263
-1121
lines changed

‎vue2-tutorials/single-file/demo2/.vs/VSWorkspaceState.json

Copy file name to clipboardExpand all lines: vue2-tutorials/single-file/demo2/.vs/VSWorkspaceState.json
-11Lines changed: 0 additions & 11 deletions
This file was deleted.

‎vue2-tutorials/single-file/demo2/.vs/demo2/config/applicationhost.config

Copy file name to clipboardExpand all lines: vue2-tutorials/single-file/demo2/.vs/demo2/config/applicationhost.config
-974Lines changed: 0 additions & 974 deletions
This file was deleted.
Binary file not shown.

‎vue2-tutorials/single-file/demo2/.vs/demo2/v17/DocumentLayout.backup.json

Copy file name to clipboardExpand all lines: vue2-tutorials/single-file/demo2/.vs/demo2/v17/DocumentLayout.backup.json
-41Lines changed: 0 additions & 41 deletions
This file was deleted.

‎vue2-tutorials/single-file/demo2/.vs/demo2/v17/DocumentLayout.json

Copy file name to clipboardExpand all lines: vue2-tutorials/single-file/demo2/.vs/demo2/v17/DocumentLayout.json
-92Lines changed: 0 additions & 92 deletions
This file was deleted.
Binary file not shown.

‎vue2-tutorials/single-file/demo2/src/App.vue

Copy file name to clipboardExpand all lines: vue2-tutorials/single-file/demo2/src/App.vue
+5-3Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
<Demo3 /> -->
88
<!-- <Demo4 /> -->
99
<!-- <Demo6 /> -->
10-
<Todo />
10+
<!-- <Todo /> -->
11+
<Demo8 />
1112
</div>
1213
</template>
1314

@@ -17,11 +18,12 @@
1718
// import Demo3 from "@/views/demo3/index.vue";
1819
// import Demo4 from "@/views/demo4/index.vue";
1920
// import Demo5 from "@/views/demo5/index.vue";
20-
import Todo from "@/views/todo/index.vue";
21+
// import Todo from "@/views/todo/index.vue";
22+
import Demo8 from "@/views/demo8/index.vue";
2123
2224
export default {
2325
name: "App",
2426
// components: { Demo1, Demo2, Demo3 },
25-
components: { Todo },
27+
components: { Demo8 },
2628
};
2729
</script>
+174Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
# Vue2 组件通信与事件处理最佳实践
2+
3+
## 一、事件系统核心机制
4+
5+
### 1. 事件修饰符对比
6+
| 修饰符 | 说明 | 示例 |
7+
| ---------- | ------------ | --------------------------- |
8+
| `.once` | 只触发一次 | `@click.once="handler"` |
9+
| `.native` | 监听原生事件 | `@click.native="handler"` |
10+
| `.stop` | 阻止事件冒泡 | `@click.stop="handler"` |
11+
| `.prevent` | 阻止默认行为 | `@submit.prevent="handler"` |
12+
13+
### 2. 事件绑定与解绑
14+
```javascript
15+
// 子组件 StudentInfo.vue
16+
methods: {
17+
emitEvent() {
18+
this.$emit('custom-event', payload)
19+
},
20+
unbind() {
21+
this.$off('custom-event') // 解绑特定事件
22+
this.$off() // 解绑所有事件
23+
}
24+
}
25+
```
26+
27+
## 二、组件通信模式详解
28+
29+
### 1. Props 向下传递
30+
```javascript
31+
// 父组件
32+
<Child :title="pageTitle" />
33+
34+
// 子组件
35+
props: {
36+
title: {
37+
type: String,
38+
default: '默认标题'
39+
}
40+
}
41+
```
42+
43+
### 2. Events 向上通信
44+
```javascript
45+
// 子组件
46+
this.$emit('update', newValue)
47+
48+
// 父组件
49+
<Child @update="handleUpdate" />
50+
```
51+
52+
### 3. 高级通信方式
53+
| 方式 | 适用场景 | 示例 |
54+
| -------------- | ---------- | ------------------------------------- |
55+
| ref | 父调子方法 | `this.$refs.child.method()` |
56+
| provide/inject | 跨级组件 | `provide() { return { key: value } }` |
57+
| Event Bus | 任意组件 | `Vue.prototype.$bus = new Vue()` |
58+
| Vuex | 全局状态 | `this.$store.commit('mutation')` |
59+
60+
## 三、最佳实践指南
61+
62+
### 1. 事件命名规范
63+
- 使用 kebab-case 命名(如 `user-updated`
64+
- 避免与原生事件重名(如 `click`
65+
- 语义化命名(如 `form-submitted`
66+
67+
### 2. 性能优化建议
68+
```javascript
69+
// 1. 适时解绑事件
70+
beforeDestroy() {
71+
this.$off('custom-event')
72+
}
73+
74+
// 2. 防抖处理高频事件
75+
methods: {
76+
handleInput: _.debounce(function() {
77+
// 处理逻辑
78+
}, 500)
79+
}
80+
```
81+
82+
### 3. 安全通信模式
83+
```javascript
84+
// 添加事件存在性检查
85+
if (this._events['custom-event']) {
86+
this.$emit('custom-event', data)
87+
}
88+
```
89+
90+
## 四、高级应用场景
91+
92+
### 1. 动态事件处理
93+
```javascript
94+
// 根据条件绑定不同处理函数
95+
<template>
96+
<Child @event="handlerMap[handlerType]" />
97+
</template>
98+
99+
<script>
100+
export default {
101+
data() {
102+
return {
103+
handlerType: 'typeA',
104+
handlerMap: {
105+
typeA: this.handleTypeA,
106+
typeB: this.handleTypeB
107+
}
108+
}
109+
}
110+
}
111+
</script>
112+
```
113+
114+
### 2. 自定义事件总线
115+
```javascript
116+
// event-bus.js
117+
import Vue from 'vue'
118+
export const EventBus = new Vue()
119+
120+
// 组件A
121+
EventBus.$emit('message', 'Hello')
122+
123+
// 组件B
124+
EventBus.$on('message', (msg) => {
125+
console.log(msg)
126+
})
127+
```
128+
129+
### 3. 异步事件处理
130+
```javascript
131+
// 返回Promise的事件处理
132+
methods: {
133+
async submitForm() {
134+
try {
135+
await this.$emitAsync('form-submit')
136+
this.showSuccess()
137+
} catch (error) {
138+
this.showError(error)
139+
}
140+
}
141+
}
142+
```
143+
144+
## 五、常见问题解决方案
145+
146+
1. **事件未触发排查**
147+
- 检查事件名称大小写是否一致
148+
- 确认子组件是否正确调用 `$emit`
149+
- 验证父组件监听的事件名是否匹配
150+
151+
2. **内存泄漏预防**
152+
```javascript
153+
// 清除所有监听器
154+
beforeDestroy() {
155+
this.$off()
156+
EventBus.$off('event', this.handler)
157+
}
158+
```
159+
160+
3. **跨组件通信优化**
161+
```javascript
162+
// 使用Vue.observable实现轻量状态管理
163+
const state = Vue.observable({ count: 0 })
164+
```
165+
166+
## 六、与Vue3的对比
167+
168+
| 特性 | Vue2 | Vue3 |
169+
| -------- | ----------- | ---------------- |
170+
| 事件系统 | `$emit/$on` | `emits` 选项声明 |
171+
| 移除API | - | `$off`, `$once` |
172+
| 新特性 | - | `v-model` 参数 |
173+
| 性能 | 基于观察者 | 基于Proxy |
174+

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.