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

  https://github.com/zh-lx/pinyin-pro

posted @   ·休伯利安  阅读(363)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示