vue中 ComponentCustomProperties运用实例详解

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'))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值