【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>
相关推荐
持续升级打怪中17 分钟前
Vue3 中虚拟滚动与分页加载的实现原理与实践
前端·性能优化
GIS之路21 分钟前
GDAL 实现矢量合并
前端
hxjhnct23 分钟前
React useContext的缺陷
前端·react.js·前端框架
冰暮流星31 分钟前
javascript逻辑运算符
开发语言·javascript·ecmascript
前端 贾公子1 小时前
从入门到实践:前端 Monorepo 工程化实战(4)
前端
菩提小狗1 小时前
Sqlmap双击运行脚本,双击直接打开。
前端·笔记·安全·web安全
前端工作日常1 小时前
我学习到的AG-UI的概念
前端
韩师傅1 小时前
前端开发消亡史:AI也无法掩盖没有设计创造力的真相
前端·人工智能·后端
XiaoYu20021 小时前
第12章 支付宝SDK
前端
双向332 小时前
RAG的下一站:检索增强生成如何重塑企业知识中枢?
前端