0
1

More than 3 years have passed since last update.

【Nuxt.js】filter実践編:文末を…で省略しよう!

Last updated at Posted at 2020-01-10

前置き

スクリーンショット 2020-01-08 14.30.24.png

filterを使って
文末を…(三点リーダー)で省略してみます🌟
コードの後にそれぞれの
各ポイントで解説をしていきます。

【考え方】
文字の長さlengthが
・10文字まで(0〜9)はそのまま表示
・11文字目以降(10〜)も続くなら
  10文字目まではそのまま表示
  11文字目を…にする

CSSでもできるよね?

できます!
が、
基準が字数ではなく、行数や幅になります。
https://www.yoheim.net/blog.php?q=20180702

コード(ローカルver)

sliceが分かりやすいよう
data内テキストは数字の0〜にしました。
では後ろの解説をどうぞ。

index.vue
<template>
 <div class="page">
   {{ text | omittedText }}
 </div>
</template>

<script>
export default {
 data () {
   return {
     text: "0123456789101112",
   }
 },
  filters: {
    omittedText(text) {
     return text.length > 10 ? text.slice(0, 10) + "" : text;
    },
  },
}
</script>

<style lang="scss" scoped>
</style>

filter

https://note.com/aliz/n/ncaab37ed5ef5
基本的な使い方をご確認ください!

前回には記載していない点があります。
filterにはthisを書けず
dataに直接アクセスできないことです。

そのためthis.textとは書けません。
その代わりに引数にtextを渡しています。

slice

sliceを使って、
指定文字を抜き出します。
今回は10文字目まで(0〜9)を表示🍒
slice(0, 10) でOKです♪

sliceの意味は…
指定番号〜後ろの指定番号より前を抜き出す🌟

slice(2) = 2番目〜を抜き出す
slice(0, 10) = 0番目〜9文字目までを抜き出す

MDNが参考になります!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice#Examples

三項演算

◾️式1 ? 式2 : 式3
  式1が
  ・trueなら式2
  ・falseなら式3

今回は文字の長さによって条件分岐させます。

文字の長さ ? 10文字まではそのまま表示 + 11文字目以降は"…" : 10文字まではそのまま表示 ;

これをコードにすると

text.length > 10 ? text.slice(0, 10) + "…" : text;

◾️式1:文字の長さlengthが10文字より多い
(より、なので10は含まず11〜)
・trueなら式2 10文字まではそのまま表示
        11文字目を…にする
・falseなら式3 10文字目まではそのまま表示

20文字目を…にしたい場合

【index.vue】
filterの数字を変更しましょう!
sliceが慣れてくれば簡単ですね🍒

index.vue
// 変更前
return text.length > 10 ? text.slice(0, 10) + "…" : text;

// 変更後
return text.length > 19 ? text.slice(0, 19) + "…" : text;

コード(グローバルver)

plugin/filter.js
import Vue from 'vue'

Vue.filter('toLowercase', function (text) {
 return text.length > 10 ? text.slice(0, 10) + "" : text;
})
nuxt.config.js
export default {
 plugins: [
   '~/plugins/filter.js'
 ],
}
index.vue
<template>
 <div class="page">
   {{ text | omittedText }}
 </div>
</template>

<script>
export default {
 data () {
   return {
     text: "0123456789101112",
   }
 },
}
</script>

<style lang="scss" scoped>
</style>

このアカウントでは
Nuxt.js、Vue.jsを誰でも分かるよう、
超簡単に解説しています🎈😀
これからも発信していくので、
ぜひフォローしてください♪

https://twitter.com/aLizlab

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1