Vue.js 独自ディレクティブを作成する

Vue.js 独自ディレクティブを作成する

Vue.jsで、独自ディレクティブを作成するサンプルコードを記述してます。 「vue3」を使用してます。

環境

  • OS windows10 pro 64bit
  • Vue.js 3.2.2
  • Apache 2.4.43
  • ブラウザ chrome 101.0.4951.67

独自ディレクティブを作成する

独自ディレクティブを作成するには、「directives」を使用します。

以下は、 独自ディレクティブ 「v-fstyle」で、fontのサイズを「50px」に設定するサンプルコードとなります。

※「vue3」は「cdn版」、デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>

  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <script src="https://unpkg.com/vue@next"></script>

</head>
<style>
  body>.grid {
    height: 100%;
  }
</style>

<body>
  <div id="app" class="ui middle aligned center aligned grid">

    <div class="column">
      
      <h2 v-fstyle class="ui gray header">{{val}}</h2>

    </div>

  </div>
  <script>

    const hoge = {
      data() {
        return {
          val: 'mebee'
        }
      },
      directives: {
        fstyle: {          
          mounted(e) {
            e.style.fontSize = '50px'
          }
        }
      }
    }

    Vue.createApp(hoge).mount('#app')

  </script>
</body>

</html>

fontのサイズが変更されていることが確認できます。