LoginSignup
1
1

More than 3 years have passed since last update.

vue.jsでリンク先の拡張子でFont Awesome Iconが変わるあいつをつくってみた

Last updated at Posted at 2020-03-13

具体的にどんなの?

a[href$=".pdf"]のようなCSSの疑似要素を利用してアイコンを表示していた下記のようなやつを
vue-fontawesomeを利用して作ってみよう、というお話です。
アートボード 1.png

Q:今まで通りCSSの疑似要素で実装すればいいじゃん

A:それじゃこの記事の意味ないでしょ:upside_down:
疑似要素はエラー発生しやすいからお勧めしない(意訳)書いてあるからね。つべこべ言わずに勉強のつもりで考えてみよう。

実際に作ってみた

拡張子のパターン振り分けどうしよう、いくつまで対応したらいいんだろうと考えてたら、font-awesome-filetypesという素敵なものを発見したので利用したところあっという間でできてしまった。

linkFileIcon.vue
<template>
  <a :href="href">
    <font-awesome-icon
      :icon="faIcon(href)"
      :class="`text-` + faIconColor()"
      fixed-width
    /><slot v-slot="text">{{ text.label }}</slot>
  </a>
</template>
<script>
import geticonForExtension from "font-awesome-filetypes";
export default {
  name: "href",
  props: {
    label: {
      type: String,
      default: "リンク"
    },
    href: String
  },
  methods: {
    isExternalLink(path) {
      //外部リンクかどうか
      return /^https?:\/\//.test(path);
    },
    faIcon(path) {
      if (path) {
        //外部リンクの場合は"external-link-alt"
        if (this.isExternalLink(path)) {
          return "external-link-alt";
        } //それ以外は拡張子によってアイコンを変更
        return geticonForExtension(path.split(".").pop()).slice(3);
      }//拡張子が判別できない場合は"file"
      return "file";
    },
    faIconColor() {
      //アイコンごとに色を変更、BootstrapVueを使用しています
      const faIcon = this.faIcon(this.href);
      if (faIcon === `external-link-alt` || faIcon === `file-word`) {
        return `info`;
      } else if (faIcon === `file-powerpoint`) {
        return `warning`;
      } else if (faIcon === `file-excel`) {
        return `success`;
      } else if (faIcon === `file-video` || faIcon === `file-pdf`) {
        return `danger`;
      } else if (!this.href) {
        return `muted`;
      } else return `primary`;
    }
  }
};
</script>

ポストカードウェア

font-awesome-filetypesは、自由に使っていいけど、役に立ったら使ったパッケージ書いた手紙送ってね(意訳)と書いてあるので、もし利用したら送ってあげてね。私もそうするつもり。
いっぱいあって楽しいね

1
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
1
1