05订阅发布模式
# 订阅发布模式
js设计模式-订阅发布模式
eventBus.$emit("事件名",数据)eventBus.$on("事件名",(数据)=>{数据})
# 手动
父组件
// src/App.vue
<template>
<test></test>
</template>
<script>
import test from "./components/test.vue";
import eventBus from "./utils/eventBus.js";
export default {
components: {
test,
},
setup() {
eventBus.$emit("aevent", "我是父组件传给子组件的数据——>");
eventBus.$emit("bevent", "我是父组件传给子组件的数据——>");
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
订阅发布写法
// src/utils/eventBus.js
class EventBus {
constructor() {
this.list = [];
}
$emit(eventName, payload) {
setTimeout(() => {
this.list.forEach((item) => {
if (item.eventName === eventName) {
item.callBack(payload);
}
});
}, 0);
}
$on(eventName, callBack) {
this.list.push({
eventName,
callBack,
});
$off(eventName) {
this.list.forEach((item, idx) => {
if (item.eventName === eventName) {
// this.list.splice(idx, 1);
this.list.splice(idx, item);
}
});
}
}
export default new EventBus();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
子组件
// src/components/test.vue
<template>
<div>我是子组件</div>
</template>
<script>
import eventBus from "../utils/eventBus.js";
export default {
setup() {
eventBus.$on("aevent", (res) => {
console.log(res);
});
eventBus.$on("bevent", (res) => {
console.log(res);
});
eventBus.$off("aevent");
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 插件
安装
npm
npm install tiny-emitter --save
1
创建文件
// src/utils/event.js
import emitter from "tiny-emitter/instance";
export default {
$on: (...args) => emitter.on(...args),
$once: (...args) => emitter.once(...args),
$off: (...args) => emitter.off(...args),
$emit: (...args) => emitter.emit(...args),
};
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
父组件
// src/App.vue.vue
<template>
<test></test>
</template>
<script>
import { onMounted } from "vue";
import test from "./components/test.vue";
import Bus from "./utils/event.js";
export default {
components: {
test,
},
setup() {
onMounted(() => {
Bus.$emit("aevent", "我是父组件传给子组件的数据——>");
});
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
子组件
// src/components/test.vue
<template>
<div>我是子组件</div>
</template>
<script>
import { onMounted } from "vue";
import Bus from "../utils/event.js";
export default {
setup() {
Bus.$on("aevent", (res) => {
console.log(res);
});
},
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
编辑 (opens new window)
上次更新: 2023/08/06, 00:38:41