如何在 Vue3 项目配置全局方法

前言

大家都知道 Vue2 项目配置全局方法最简单就是使用【Vue.prototype.$XXX = XXX】这种实现方式。如该文章【https://blog.youkuaiyun.com/Cai181191/article/details/123797934】就是用这种方式来实现,然而 Vue3 项目实现配置全局方法可能就有点不一样了。

一、引入 Moment.js 日期处理类库并配置为全局方法

1.官网传送门

http://momentjs.cn/

2.导入依赖

npm i moment

3.示例代码

(1)/src/utils/momentUtil.js

import moment from 'moment';

const YYYY_MM_DD = (time) => {
  if (time) {
    return moment(time).format('YYYY-MM-DD')
  } else {
    return ''
  }
}

const YYYY_MM_DD__HH_mm_ss = (time) => {
  if (time) {
    return moment(time).format('YYYY-MM-DD HH:mm:ss')
  } else {
    return ''
  }
}

export {
  YYYY_MM_DD,
  YYYY_MM_DD__HH_mm_ss
}

(2)main.js

// 引入格式化时间工具并配置为全局方法
import * as momentUtil from '@/utils/momentUtil'
app.config.globalProperties.$momentUtil = momentUtil

4.使用方式

<div>{{ $momentUtil.YYYY_MM_DD(scope.row.createTime) }}</div>


二、生成字符串对应的颜色值并配置为全局方法

1.示例代码

(1)/src/utils/colorUtil.js

const stringToColor = (str) => {
  if (str) {
    let hash = 0
    for (var i = 0; i < str.length; i++) {
      hash = hash * 31 + str.charCodeAt(i)
      hash = intValue(hash)
    }
    let r = (hash & 0xFF0000) >> 16
    let g = (hash & 0x00FF00) >> 8
    let b = (hash & 0x0000FF)
    return 'rgba(' + r + ',' + g + ',' + b + ',' + '0.2)'
  } else {
    return 'transparent' // 透明
  }
}

function intValue(num) {
  var MAX_VALUE = 0x7fffffff;
  var MIN_VALUE = -0x80000000;
  if (num > MAX_VALUE || num < MIN_VALUE) {
    return num &= 0xFFFFFFFF;
  }
  return num;
}

export {
  stringToColor
}

(2)main.js

// 引入颜色工具并配置为全局方法
import * as colorUtil from '@/utils/colorUtil'
app.config.globalProperties.$colorUtil = colorUtil

2.使用方式

<p :style="'color: ' + $colorUtil.stringToColor('HelloWorld')">HelloWorld</p>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值