1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

bootstap-vueで内部リンクと外部リンクでプロパティが切り替わるやつを作ってみた

Posted at

概要

BootstrapVueには通常の<a>タグリンクと<router-link>両方をサポートしている<b-link>があるけど1、それぞれhrefとtoとプロパティが違うので、v-forなどでリスト化する時わざわざ書き分けるのがめんどくさい非効率なので一つにまとめられないかなと考えた。

できたもの

タグ切り替えだけじゃもったいないので外部リンク時は新しいタブでひらいて、Font Awesomeを使ってアイコンつけるようにしたよ

LinkPath.vue
<template>
  <b-link :[bind]="path" :target="isExternalLink ? '_new' : '_self'">
  <slot></slot>
    <font-awesome-icon v-if="isExternalLink" icon="external-link-alt" />
  </b-link>
</template>
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
  props: {
    path: { type: String },
  },
  computed: {
    bind(): string {
      return this.isExternalLink(this.path) ? `href` : `to`;
    },
    isExternalLink(): boolean {
      return /^https?:\/\//.test(this.path);
    },
  },
});
</script>

余談

Q:フレームワーク使わないとダメなの?

A:<component :is="bind"~2利用してタグそのもの切り替えれば同じようにできるはず。知らんけど。

Q:なんでTypeScript?

A:JavaScriptよりTypeScriptのほうがミスが少なくなるらしい、勉強するなら早いに越したことないしね。乗らなきゃこのビックウェーブに
デコレーターを使うとよりTypeScriptらしく記述できるらしいけど、将来どうなるか分からない3ので今回はVue.extendを利用したよ

参考リンク

  1. BootstrapVue│Links│Component reference

  2. Vue.js公式:動的 & 非同期コンポーネント

  3. the Class API proposal is being dropped.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?