Vue3 定义全局函数和变量

globalProperties

由于Vue3 没有Prototype 属性 使用 app.config.globalProperties 代替 然后去定义变量和函数


// man.ts

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

let app = createApp(App)

type Filters = {
    format: <T>(str: T) => T
  }


// 声明要扩充@vue/runtime-core包的声明 扩充"ComponentCustomProperties"接口, 因为他是vue3中实例的属性的类型.
declare module '@vue/runtime-core' {
    export interface ComponentCustomProperties {
        $filters: Filters,
        $vn: string
    }
}


app.config.globalProperties.$filters = {
    format<T>(str: T):string {
        return `我是${str}`
      }
} 

app.config.globalProperties.$vn = '小黑'

app.mount('#app')


<template>
  <div>
    <div>{{$filters.format('1111')}}</div>
  <div>{{ $vn }}</div>
  </div>
</template>

<script setup lang="ts">
// 取出全局定义的值
import { getCurrentInstance, ComponentInternalInstance } from 'vue';
 
const { appContext } = <ComponentInternalInstance>getCurrentInstance()
  
console.log(appContext.config.globalProperties.$vn);
</script>

<style scoped>

</style>

你可能感兴趣的:(javascript,vue.js,前端)