index2.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <template>
  2. <!-- index.wxml -->
  3. <view class="container">
  4. <view class="info-container">
  5. <text class="pinyin-text">{{ pinyinText }}</text>
  6. <input ref="inp" id="inp" :value="inputValue" :focus="isFocus" maxlength="1" @input="onInput" placeholder=" " />
  7. <text class="tip">输入汉字</text>
  8. </view>
  9. </view>
  10. </template>
  11. <script>
  12. // index.js
  13. var app = getApp();
  14. var pinyin = require('./pinyin.js');
  15. export default {
  16. data() {
  17. return {
  18. pinyinText: '',
  19. inputValue: '',
  20. isFocus: false
  21. };
  22. },
  23. onLoad: function () {
  24. // 保证进入页面时输入框为空
  25. this.inputValue = '';
  26. this.pinyinText = '';
  27. },
  28. onReady: function () {
  29. // H5端用ref聚焦,微信小程序端用布尔focus控制
  30. // #ifdef H5
  31. this.$nextTick(() => {
  32. if (this.$refs.inp && typeof this.$refs.inp.focus === 'function') {
  33. this.$refs.inp.focus();
  34. }
  35. });
  36. // #endif
  37. // #ifdef MP-WEIXIN
  38. this.$nextTick(() => {
  39. this.isFocus = true;
  40. });
  41. // #endif
  42. },
  43. methods: {
  44. // 事件处理函数
  45. onInput: function (e) {
  46. const val = e && e.detail ? e.detail.value : '';
  47. const char = typeof val === 'string' ? val.trim() : '';
  48. this.inputValue = char;
  49. if (char.length == 1) {
  50. if (pinyin.hasOwnProperty(char)) {
  51. this.pinyinText = pinyin[char].join(', ');
  52. } else {
  53. this.pinyinText = '找不到,^_^';
  54. }
  55. } else {
  56. this.pinyinText = '';
  57. }
  58. }
  59. }
  60. };
  61. </script>
  62. <style>
  63. @import './index.css';
  64. </style>