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组件的其他用法,可参考链接:

浙公网安备 33010602011771号