ComponentCustomProperties
1、全局挂载mit
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import './assets/main.css'
import mitt from 'mitt'
const Mit = mitt()
const app = createApp(App)
// 类型声明
declare module 'vue' {
export interface ComponentCustomProperties {
$Bus: typeof Mit
}
}
app.use(createPinia())
app.config.globalProperties.$Bus = Mit
app.mount('#app')
2、A组件传递数值
<script setup lang="ts">
import { getCurrentInstance, ref } from 'vue'
const instance = getCurrentInstance()
const flag = ref(1)
const Pass = () => {
instance?.proxy?.$Bus.emit('pass', flag)
}
</script>
<template>
<div>
我是A
<div>{{ flag }}</div>
<button @click="Pass">Pass</button>
</div>
</template>
<style scoped lang="less"></style>
3、B组件接收数值
<script setup lang="ts">
import { getCurrentInstance, ref, type Ref } from 'vue'
const instance = getCurrentInstance()
const flag = ref(0)
instance?.proxy?.$Bus.on('pass', Flag => {
flag.value = (Flag as Ref<number>).value
})
</script>
<template>
<div>
我是B
<div>{{ flag }}</div>
<button @click="flag++">+</button>
</div>
</template>
<style scoped lang="less"></style>
6、取消监听事件
<script setup lang="ts">
import { getCurrentInstance, ref, type Ref } from 'vue'
const instance = getCurrentInstance()
const flag = ref(0)
instance?.proxy?.$Bus.off('pass', Flag => {
flag.value = (Flag as Ref<number>).value
})
</script>
7.取消全部监听事件
<script setup lang="ts">
import { getCurrentInstance, ref, } from 'vue'
const instance = getCurrentInstance()
instance?.proxy?.$Bus.all.clear()
</script>
8、读值
第一种方式:
import { getCurrentInstance, ComponentInternalInstance } from 'vue';
const { appContext } = <ComponentInternalInstance>getCurrentInstance()
console.log(appContext.config.globalProperties.$env);
推荐第二种方式:
import {ref,reactive,getCurrentInstance} from 'vue'
const app = getCurrentInstance()
console.log(app?.proxy?.$Bus.format('js'))