uni app 显示中文拼音的组件 py-text-view (pinyin-pro)

说白了就是用了 pinyin-pro 插件 封装了一个view而已,直接看代码~~

pinyin-pro是一个很不错的插件,我们只需要安装(npm install pinyin-pro )就即可
中文转拼音、拼音音调、拼音声母、拼音韵母、多音字拼音、姓氏拼音、拼音匹配
插件地址:https://github.com/zh-lx/pinyin-pro

效果图:

1.你需要先安装pinyin-pro插件:

npm install pinyin-pro

2.组件代码

components/py-text-view/index.vue

<template>
  <view @click="onTab" class="py-item-box">
    <block v-if="isChinese(data)">
      <view class="item" v-for="(item, index) in getDataList()" :key="index">
        <view style="font-size: 28rpx; height: 30rpx">
          {{ item.pin || '' }}
        </view>
        <view class="">
          {{ item.text || '' }}
        </view>
      </view>
    </block>
    <view v-else>
      {{ data }}
    </view>
  </view>
</template>

<script lang="ts">
import Vue from 'vue';
import { pinyin } from 'pinyin-pro';
export default Vue.extend({
  props: {
    data: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chinese: true,
      textIndex: 0
    };
  },
  methods: {
    isChinese(temp: any) {
      var re = new RegExp('[\\u4E00-\\u9FFF]+', 'g');
      return re.test(temp);
    },
    getDataList() {
      var a = [];
      var noZhChar = '';

      for (var char of this.data) {
        var isCh = this.isChinese(char);
        if (isCh) {
          if (noZhChar) {
            a.push({ text: noZhChar });
            noZhChar = '';
          }
          a.push({ text: char, pin: pinyin(char) });
        } else {
          noZhChar = noZhChar + char;
        }
      }
      if (noZhChar) {
        a.push({ text: noZhChar });
        noZhChar = '';
      }
      return a;
    },

    onTab() {
      this.$emit('click');
    }
  }
});
</script>

<style lang="scss" scoped>
.py-item-box {
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  .item {
    padding-inline-end: 16rpx;
    padding-bottom: 6rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
</style>

3.引入方式:

...
import PyTextView from '@/components/py-text-view/index.vue';
...

  components: {
    PyTextView
  },

3.1使用方式:

 <py-text-view :data="data" />
 <!-- <py-text-view data="你好,我叫努尔" /> -->
 <!-- <py-text-view :data="data" @click="click" /> -->

posted @ 2022-10-29 17:10  nur01  阅读(380)  评论(0编辑  收藏  举报