1. 下载依赖
npm install pinyin-pro
2.引入放置utils
import { pinyin, customPinyin } from 'pinyin-pro'
3. 封装方法放置在utils 处理
// 拼音处理首字母大写
function customPinyinFun(content) {
let str = []
let zhStr = /[\u4e00-\u9fa5]/ // 中文校验
let enStr = /[a-z]+/ // 小写字母校验
content.split('').forEach(
i => {
if (zhStr.test(i)) {
i = pinyin(i, { pattern: 'first', toneType: 'none' }).toUpperCase() // 转成首字母大写
} else if (enStr.test(i)) {
i = i.toUpperCase() // 小写转大写
} else {
i
}
str.push(i)
})
return str.join('')
}
4. 页面使用
import { customPinyinFun } from '@/utils/utils'
customPinyinFun('测试数据')
// 结果 CSSJ