zheng 6 дней назад
Родитель
Сommit
c8ce4529f1

+ 1 - 0
17.Vue3/project3/package.json

@@ -14,6 +14,7 @@
     "type-check": "vue-tsc --build"
   },
   "dependencies": {
+    "mitt": "^3.0.1",
     "sass": "^1.97.2",
     "scss": "^0.2.4",
     "vue": "^3.5.26",

+ 24 - 0
17.Vue3/project3/src/utils/emitter.js

@@ -0,0 +1,24 @@
+import mitt from 'mitt'
+
+const emitter = mitt()
+
+// listen to an event 收听一个事件
+emitter.on('foo', e => console.log('foo', e) )
+
+// listen to all events
+emitter.on('*', (type, e) => console.log(type, e) )
+
+// fire an event 发起一个事件
+emitter.emit('foo', { a: 'b' })
+// clearing all events
+emitter.all.clear()
+
+
+export default emitter;
+
+
+
+// working with handler references:
+// function onFoo() {}
+// emitter.on('foo', onFoo)   // listen
+// emitter.off('foo', onFoo)  // unlisten

+ 19 - 0
17.Vue3/project3/src/views/Mitt/Child1.vue

@@ -0,0 +1,19 @@
+<template>
+  <div>
+    <h1>Child1</h1>
+    <h3>我有{{ money }}元</h3>
+    <button @click="handleMoney">给兄弟一半</button>
+  </div>
+</template>
+
+<script lang="ts" setup>
+import {ref,reactive} from "vue" 
+import emitter from "@/utils/emitter"
+let money = ref(1000);
+const handleMoney = () => {
+    emitter.emit('aa',money.value / 2)
+}
+</script>
+
+<style lang="scss" scoped>
+</style>

+ 22 - 0
17.Vue3/project3/src/views/Mitt/Child2.vue

@@ -0,0 +1,22 @@
+<template>
+  <div>
+    <h1>Child2</h1>
+    <h3>我收到了兄弟的红包:{{ red }}元</h3>
+  </div>
+</template>
+
+<script lang="ts" setup>
+import emitter from "@/utils/emitter"
+import {ref,onUnmounted} from "vue" 
+let red = ref(0)
+emitter.on('aa',(val:number)=>{
+    console.log('收到兄弟的红包')
+    red.value = val;
+})
+onUnmounted(()=>{
+    emitter.off('aa')
+})  
+</script>
+
+<style lang="scss" scoped>
+</style>

+ 12 - 1
17.Vue3/project3/src/views/Mitt/Father.vue

@@ -1,12 +1,23 @@
 <template>
   <div>
     <h1>Mitt</h1>
+    <hr>
+    <hr>
+    <hr>
+    <hr>
+    <Child1></Child1>
+    <hr>
+    <hr>
+    <hr>
+    <hr>
+    <Child2></Child2>
   </div>
 </template>
 
 <script lang="ts" setup>
 import {ref,reactive} from "vue" 
-
+import Child1 from "./Child1.vue"
+import Child2 from "./Child2.vue"
 </script>
 
 <style lang="scss" scoped>