のぐそんブログ

暗いおじさんがシコシコ書くブログです。

vueのカスタムディレクティブのメモ

カスタムディレクティブ

v-xxxのようなオリジナルのディレクティブを作成することができる。

ディレクティブのオプション

オプション 内容
bind ディレクティブが対象の要素に紐付いたときに1度だけ実行される
inserted 紐ついた要素が挿入されたタイミングで呼ばれる
update ディレクティブの値の変化などに伴って紐ついた要素を含んでいるコンポーネントのVNodeが更新されるタイミングで呼ばれる
componentUpdated コンポーネントのVNodeが更新されたタイミングで呼ばれる
unbind ディレクティブが紐ついた要素から取り除かれたタイミングで呼ばれる

フック関数の引数

引数名 内容
el ディレクティブが紐づく要素
binding 後述

bindingのプロパティ

プロパティ 内容
name prefixなし(v-)のディレクティブ名
velue ディレクティブに渡される値
modifiers 修飾子。v-hoge.fugaなら{fuga:true}となる

※一部です

実装例1) スタイルを設定する

directive.js

ここではグローバルにディレクティブを登録する。

import Vue from 'vue'

Vue.directive('sample',{
  bind: function (el) { 
    el.style.backgroundColor = "red"
  }
})

ディレクティブを利用するには、他と同じくv-をprefixとしてつける。

<template>
  <div>
    <div v-bind:style="hoge" v-sample>テスト</div>
  </div>
</template>
<style>
</style>
<script>
export default {
  data: function() {
    return {
      hoge:'font-size:30px'
    };
  },
};
</script>

結果

f:id:nogson2:20190110170159j:plain

実装例2) 画像がない場合にno imageを出すディレクティブ

Vue.directive('no-image',{
  bind: function (el) { 
    el.addEventListener('error',function(){
      el.src="assets/noimage.png"
    })
  }
})

assets/logo.pngは無いものとする。

<template>
  <div>
    <img v-no-image src="assets/logo.png">
  </div>
</template>

結果

f:id:nogson2:20190110170204j:plain

参考

Vue.js入門 基礎から実践アプリケーション開発まで