Vue3 + TypeScript 定义全局方法
  U29JGNzm80ru 2023年11月02日 36 0

创建一个全局方法

app.config.globalProperties.$dateFormat = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

创建一个文件,用于调用公共方法

import { ComponentInternalInstance, getCurrentInstance } from 'vue'

export const useCurrentInstance = () => {
  const { appContext } = getCurrentInstance() as ComponentInternalInstance
  const proxy = appContext.config.globalProperties
  return {
    proxy
  }
}

使用

<template>
  <div>
    {{ proxy?.$dateFormat(date) }}
  </div>
</template>

<script setup lang="ts">
import { useCurrentInstance } from '@/utils/useCurrentInstance'

const { proxy } = useCurrentInstance()
</script>
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  gYl4rku9YpWY   2024年05月17日   57   0   0 Vue
  JZjRRktyDDvK   2024年05月02日   80   0   0 Vue
  VlNAKfyhjjp9   2024年04月30日   76   0   0 Vue
  JNTrZmaOQEcq   2024年04月30日   54   0   0 Vue
  onf2Mh1AWJAW   2024年05月17日   59   0   0 Vue
  3A8RnFxQCDqM   2024年05月17日   58   0   0 Vue
U29JGNzm80ru
作者其他文章 更多