LoginSignup
3
1

More than 5 years have passed since last update.

router-linkで外部リンクも内部リンクも済ませてしまいたい時の対処法

Posted at

上記英語質問サイトの丸パクリですが、対応する日本語記事が見つからなかったので、メモ代わりに投稿させてください。

コード

vue.js
<template>
  <component v-bind:is="linkProps(to)">
      <slot></slot>
  </component>
</template>

<script>
  export default {
    props: {
      to: {
        type: String,
        required: true,
      },
    },
    methods: {
      linkProps(url)
      {
        if (url.match(/^(http(s)?|ftp):\/\//))
        {
          return {
            is: 'a',
            href: url,
            target: '_blank',
            rel: 'noopener',
          };
        }
        return {
          is: 'router-link',
          to: url,
        };
      },
    },
  };
</script>

必要な箇所に毎回メソッドを書く方法もありますが、多用するようであればコンポーネントにしておいた方が使いまわしが楽かもしれません。

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