vue3的全局组件,函数和变量

vue3的全局组件,函数和变量

全局组件:

use关键字

import MyUI from '@/components'
const app = createApp(App)
app.use(MyUI )
app.mount('#app')

全局函数和变量

vue3注册全局使用globalProperties关键字

具体使用方法

(1)main.js:

app.config.globalProperties.$[最定义函数、变量等] = ...

(2)使用的时候直接注册会报错,这是因为我们没有写声明无法正确的推导,因此我们要在main.js里面添加

type Filter = {
    format: <T extends any>(str: T) => T
  }
  
// 声明要扩充@vue/runtime-core包的声明.
// 这里扩充"ComponentCustomProperties"接口, 因为他是vue3中实例的属性的类型.
  declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        $filters: Filter,
        $name : string
    }
  }

//注册全局函数filter
app.config.globalProperties.$filters = {
  format<T extends any>(str: T): string {
    return `$${str}`
  }
}
//注册全局函数变量
app.config.globalProperties.$name = 'mina'
}

此时如果还是有红色划线,重新启动vscode即可。

(3)注册完成之后,我们就可以在文件中直接使用了

<template>
  <div>
    {{$filters}}
    {{$env}}
  </div>
</template>

<script>
import { getCurrentInstance, ComponentInternalInstance } from 'vue'
const { appContext } = <ComponentInternalInstance>getCurrentInstance()
console.log(appContext.config.globalProperties.$env);
<script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值