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>