【Vue3】定义全局变量和全局函数

ts 复制代码
// main.ts
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)

// 解决 ts 报错
type Filter = {
  format<T>(str: T): string
}
declare module 'vue' {
  export interface ComponentCustomProperties {
    $filters: Filter,
    $myArgs: string
  }
}

app.config.globalProperties.$myArgs = 'args'
app.config.globalProperties.$filters = {
  format<T>(str: T) {
    return `xiuxiu-${str}`
  }
}
app.mount('#app')
html 复制代码
<!-- App.vue -->
<template>
  <div>
    {{ $myArgs }}
    <hr>
    {{ $filters.format('的杯子') }}
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue';
const app = getCurrentInstance()
// 利用组件实例输出{{ $filter.format('的杯子') }}
console.log(app?.proxy?.$filters.format('的杯子'));
</script>

<style scoped></style>
相关推荐
Jackson__20 分钟前
聊聊 JS 中的可选链 ?.
前端
前端小崔26 分钟前
前端面试题之ES6保姆级教程
开发语言·前端·javascript·面试·职场和发展·ecmascript·es6
Bug从此不上门35 分钟前
【无标题】
前端·javascript·uni-app·vue
HarderCoder35 分钟前
ByAI:Redux中间件的原理和ts简化实现
前端·redux
贩卖纯净水.38 分钟前
Webpack依赖
前端·webpack·node.js
crary,记忆40 分钟前
微前端 - Module Federation使用完整示例
前端·react·angular
不知几秋1 小时前
Spring Boot
java·前端·spring boot
程序猿ZhangSir1 小时前
Vue3 项目的基本架构解读
前端·javascript·vue.js
HarderCoder1 小时前
ByAI: Redux的typescript简化实现
前端
90后的晨仔1 小时前
RxSwift 框架解析
前端·ios