vue根据汉字添加拼音
效果如下
- 安装工具库
npm install pinyin-pro 或者 yarn add pinyin-pro
- 封装组件 change-pinyin
<template> <div class="pinyin"> <div class="wordBox" v-for="(item,index) in list" :key="index"> <ruby>{{item['hanzi']}} <rt>{{item['pinyin']}}</rt> </ruby> </div> </div> </template> <script> import { pinyin } from 'pinyin-pro'; export default { name: "change-pinyin", props: { content: String, }, mounted() { for (let char of this.content) { console.log("char==",char); let pinyins = '' // 判断是否为汉字 var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g"); if (reg.test(char)) { pinyins = pinyin(char) } this.list.push( { "hanzi": char, "pinyin": pinyins } ) } }, data() { return { list: [] } } } </script> <style scoped> .pinyin { margin: 5px; } .wordBox { width: 2.2em; display: inline-block; text-align: center; } </style>
- 引用组件
<template> <div id="app"> <change-pinyin content="我们都有一个家,名字叫中国。"></change-pinyin> </div> </template> <script> import changePinyin from './components/changePinyin.vue'; export default { name: "App", components: { changePinyin, }, mounted() { }, }; </script> <style> </style>
- pinyin-pro组件的其他用法,可参考链接:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现