官术网_书友最值得收藏!

Text stats

The last stats we can display are more "writer-oriented"--the lines, words, and characters count:

  1. Let's create three new computed properties for each counter, with some Regular Expressions to get the job done:
      computed: {
        linesCount () {
          if (this.selectedNote) {
            // Count the number of new line characters
            return this.selectedNote.content.split(/\r\n|\r|\n/).length
          }
        },

        wordsCount () {
          if (this.selectedNote) {
            var s = this.selectedNote.content
            // Turn new line cahracters into white-spaces
            s = s.replace(/\n/g, ' ')
            // Exclude start and end white-spaces
            s = s.replace(/(^\s*)|(\s*$)/gi, '')
            // Turn 2 or more duplicate white-spaces into 1
            s = s.replace(/\s\s+/gi, ' ')
            // Return the number of spaces
            return s.split(' ').length
          }
        },

        charactersCount () {
          if (this.selectedNote) {
            return this.selectedNote.content.split('').length
          }
        },
      }

Here, we added some conditions to prevent the code from running if no note is currently selected. This will avoid crashes if you use the Vue devtools to inspect the app in this case, because it will try to compute all the properties.

  1. You can now add three new stat span elements with the corresponding computed properties:
      <span class="lines">
        <span class="label">Lines</span>
        <span class="value">{{ linesCount }}</span>
      </span>
      <span class="words">
        <span class="label">Words</span>
        <span class="value">{{ wordsCount }}</span>
      </span>
      <span class="characters">
        <span class="label">Characters</span>
        <span class="value">{{ charactersCount }}</span>
      </span>

The final status bar should look like this:

主站蜘蛛池模板: 巨鹿县| 新泰市| 全南县| 石门县| 肥西县| 涞源县| 尼玛县| 扶绥县| 远安县| 星子县| 佳木斯市| 马山县| 安国市| 全州县| 望江县| 尖扎县| 开江县| 甘南县| 盈江县| 安远县| 广安市| 延吉市| 如东县| 罗田县| 平罗县| 孟州市| 东兴市| 邵阳市| 礼泉县| 达拉特旗| 凤台县| 塔河县| 克东县| 房山区| 瓦房店市| 枣强县| 吴江市| 高州市| 施秉县| 营山县| 随州市|