vue3 注册全局方法 定义全局方法

1.定义工具类

// 格式化时间
function FormatDate (time: string) {
  if (Tool.isNotEmpty(time)) {
    const date = new Date(time)
    // 注意js里面的getMonth是从0开始的
    let FormattedDateTime = null
    const year = date.getFullYear()
    const month = (date.getMonth() + 1)
    const day = date.getDate()
    let h: string | number = date.getHours()
    let m: string | number = date.getMinutes()
    let s: string | number = date.getSeconds()
    h = h < 10 ? '0' + h : h
    m = m < 10 ? '0' + m : m
    s = s < 10 ? '0' + s : s
    FormattedDateTime = year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s
    return FormattedDateTime
  }
  return null
}

2.在main.ts/main.js 中进行引入,并挂载全局方法

  1. 在main.ts入口文件进行引入
import { FormatDate } from '@/util/utils'

在这里插入图片描述
2. 挂载到全局方法
在这里插入图片描述
vue3 使用 app.config.globalProperties 进行全局方法的定义,全局方法定义后,就无需每个页面使用时,进行单独引用了。

const app = createApp(App)
app.config.globalProperties.$formatTime = FormatDate

3.页面使用

3.1 在template中使用时,可以直接使用

使用在main.ts定义的名称($formatTime)进行方法的引用
在这里插入图片描述

3.2 在script中使用,需要获取到 getCurrentInstance实例再进行使用

// 在main.js中,进行挂载
app.config.globalProperties.$axios = axios;

// 在页面 script使用
<script setup>
import { ref, getCurrentInstance } from 'vue'

// proxy相当于 vue2的this,从getCurrentInstance 实例中获取,proxy对象
const { proxy } = getCurrentInstance()
const getData = () => {
  proxy.$axios.get("https://www.baidu.com")
}
</script>

2021.11.29更新, 增加了在页面script中的使用方法

  • 12
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值