【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>
相关推荐
烛阴7 分钟前
你的 Express 应用还在裸奔?赶紧加上这层错误处理的保护罩!
javascript·后端·express
37手游后端团队8 分钟前
websocket连接管理
前端·后端·websocket
bin915317 分钟前
DeepSeek 助力 Vue3 开发:打造丝滑的日历(Calendar)
前端·javascript·vue.js·ecmascript·deepseek
YiHanXii19 分钟前
XSS(跨站脚本攻击)
前端·网络·xss
LinDaiuuj30 分钟前
编程中,!! 双感叹号的理解
前端·javascript
呦呦鹿鸣Rzh34 分钟前
SpringMVC的请求-文件上传
java·前端·html
samroom34 分钟前
ES6规范新特性总结
前端·javascript·es6
linpengteng43 分钟前
开发 ArkTS 版 HarmonyOS 日志库 —— logger
前端·app·harmonyos
Violet5151 小时前
前端本地DeepSeek的RAG最小化MVP - 基于Ollama+LlamaIndex实现RAG Pipeline
前端·deepseek
前端Hardy1 小时前
HTML&CSS:这个复选框打几分?
javascript·css·html