【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>
相关推荐
花开盛夏^.^1 天前
电脑打开多个浏览器Web窗口占用较大的运行内存的原因
前端·浏览器
Dxy12393102161 天前
JS DES 加密详解
开发语言·javascript·arcgis
充值内卷1 天前
我给桌面加了个鱼缸:C++ 写后端,WebView2 里养一座 Three.js 小岛
开发语言·javascript·c++
馒头不想说话1 天前
实体店老板的24小时AI运营员工,写、剪、发全自动,省下一整个团队工资
前端
椒哥1 天前
一天被问几十次"允许",我统计了 517 次,然后写了个插件
前端·javascript·github
风骏时光牛马1 天前
生成一个AI稳定性治理及疑难问题分析标题,只需要一个标题,不需要其他的任何文本。
前端
莫西干式秃头1 天前
用 AI + threejs 写了个浏览器里的 3D 动作游戏《武来》:砍怪、放技能、开 SU7
前端·人工智能·three.js
kyriewen1 天前
我测了 6 种防请求竞态的写法:只有 1 种真能打
前端·javascript·程序员
孟健1 天前
用 WorkBuddy 做个人名片网页,挂上开源设计技能后效果完全不同了
前端·人工智能·ai编程
IT_陈寒1 天前
SpringBoot自动配置的坑,这次终于爬出来了
前端·人工智能·后端