LoginSignup
5
6

More than 3 years have passed since last update.

【Nuxt.js】カスタムディレクティブ基礎編:とりあえず使ってみよう!

Posted at

前置き

スクリーンショット 2020-01-03 18.42.11.png

Vue.jsのカスタムディレクティブをNuxt.jsで!
ローカルverとグローバルverで、
どちらでも使いやすく簡単な例で紹介。
今回は背景色を変えるだけです。

…とはいえfilterはよく使われますが
実際こちらはなかなか見かけませんね。
カスタムディレクティブの良い使い方があれば
教えていただけると嬉しいです…😀

※併用する場合
同じディレクティブ名にしてしまうと
ローカルに記載された方が優先されます。
名前は分けましょう!

ローカルver

directivesで命名した物を
v-{{ name }}で記載するだけ!
今回はdiv全体に背景色をつけるため
divにv-bgを指定しております。

index.vue
<template>
  <div v-bg>
    <p>divで囲った部分の背景が変わる</p>
  </div>
</template>

<script>
export default {
 directives: {
   'bg': {
     bind(el, binding, vnode) {
       el.style.backgroundColor = 'lightgreen';
     }
   }
 },
}
</script>

グローバルver(JSファイル)

◾️パターン1
・/pluginsにjsファイルを追加
・nuxt.config.jsのpluginsに記載
・template内にv-{{ name }}を書くだけ!

file
pages/
--| index.vue

plugins/
--| bg.js

nuxt.config.js
bg.js
import Vue from 'vue'

Vue.directive('bg', {
 bind(el, binding, vnode) {
   el.style.backgroundColor = 'lightgreen';
 }
})
nuxt.config.js
plugins: [
   '~plugins/background.js'
 ],
index.vue
<template>
  <div v-bg>
    <p>divで囲った部分の背景が変わる</p>
  </div>
</template>
◾️パターン2-1
jsで直接値の指定はせず、
使用箇所で好きな値を指定できます。
bg.js

// 変更前
el.style.backgroundColor = 'green';

// 変更後
el.style.backgroundColor = binding.value;
index.vue
// 変更前
<div v-bg>

// 変更後
<div v-bg="'green'">

◾️パターン2-2
スクリーンショット 2020-01-03 19.04.43.png
argを使用した場合です。
argはpropsのようなイメージですね。
いくつもデータを渡せます♪
https://jp.vuejs.org/v2/guide/custom-directive.html#ディレクティブフック引数

bg.js
import Vue from 'vue'

Vue.directive('bg', {
 bind(el, binding, vnode) {
   // バインドされたargが文字列backgroundだった場合の処理
   if (binding.arg === 'background') {
     el.style.backgroundColor = binding.value;
   // そうでない場合の処理
   } else {
     el.style.color = binding.value;
   }
 }
})
index.vue
<template>
  <div>
    // argは:background部分
    <div v-bg:background="'lightgreen'">
      <p>背景が変わる</p>
    </div>
    <div v-bg:color="'green'">
      <p>文字色が変わる</p>
    </div>
  </div>
</template>

このアカウントでは
Nuxt.js、Vue.jsを誰でも分かるよう、
超簡単に解説しています🎈😀
これからも発信していくので、
ぜひフォローしてください♪

https://twitter.com/aLizlab

5
6
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
5
6