vue3之全局变量app.config.globalProperties的使用

本文介绍了如何在Vue应用中定义全局方法$filters,通过app.config.globalProperties设置,然后在shims-vue.d.ts中声明,以便在所有组件中使用。示例展示了如何在组件中导入并调用这个全局函数。
摘要由CSDN通过智能技术生成

1、定义全局方法

//main.ts
//定义全局方法
app.config.globalProperties.$filters = {
    //app.config.globalProperties.+你想添加的属性 $filters 加美元符号主要是为了区分和组件内部的属性
    //全局属性,在里面加东西任何地方都能用
    formatTime() {
      //格式化时间
      return '2021-12-14'
    }
  }

2、在shims-vue.d.ts声明在main.ts中定义的全局方法

/* eslint-disable */
declare module '*.vue' {
  import type { DefineComponent } from 'vue'
  const component: DefineComponent<{}, {}, any>
  export default component
  //在ComponentCustomProperties里面声明在main.ts定义的全局方法和属性
  interface ComponentCustomProperties {
    //声明全局方法
    $filters: {
      formatTime: () => string;
    }
  }
}

3、在任意组件中使用

// 部分代码
import { getCurrentInstance } from 'vue'

const instance = getCurrentInstance()
    const time =   instance?.appContext.config.globalProperties.$filters.formatTime()
    console.log(time)

4、结果展示

如有其他想法可以分享一下,谢谢

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值