開発者ドキュメント

カスタムVue.jsディレクティブの作成

Vue.jsについて話すときは、通常、コンポーネントについて話します。 コンポーネント、コンポーネント、コンポーネント。 ただし、コンポーネントはVueで記述できるのみのものではなく、それも良いことです。 コンポーネントに修飾子を適用したい場合はどうなりますか? そこで、ディレクティブが登場します。 あなたがそれを知っているかどうかにかかわらず、あなたはすでにそれらを使用しています。 v-if v-model 、およびv-forはすべてディレクティブの例です。 今日は、これなしでは生きていけない重要なタスクを実行する重要なディレクティブを追加する方法を紹介します。 その要素の背景を素敵なベイビーブルーに設定します。

ディレクティブの作成

それでは、その厚みに取り掛かりましょう。 AnnoyingBackgroundDirective.jsという名前の新しいファイルを作成します。

それでは、ディレクティブを書いてみましょう。 ディレクティブは、いくつかの特別な関数を備えた単なるオブジェクトです。

AnnoyingBackgroundDirective.js
import Vue from 'vue';

const defaultBackgroundColor = '#86bbff'

// Initialize the annoying-background directive.
export const AnnoyingBackground = {
  bind(el, binding, vnode) {
    // Allow users to customise the color by passing an expression.
    const color = binding.expression || defaultBackgroundColor

    // el might not be present for server-side rendering.
    if (el) {
      // Set the element's background color.
      el.style.backgroundColor = color
    }
  }
}

// You can also make it available globally.
Vue.directive('annoying-background', AnnoyingBackground)

コンポーネントで使用するには、v-というプレフィックスが付いたコンポーネントテンプレートに追加するだけです。

TotallyNormalComponent.vue
<template>
  <div>
    <p v-annoying-background>Baby blue looks good on me.</p>
    <p v-annoying-background="#0f0">I prefer neon green.</p>
  </div>
</template>

<script>
import { AnnoyingBackground } from './AnnoyingBackgroundDirective.js';

export default {
  directives: {
    AnnoyingBackground
  }
}
</script>

詳細

ディレクティブには5つの可能なフックがあります。

引数は次のとおりです。

そうですね、ディレクティブの作成は本当に簡単ですが、必要に応じて、ディレクティブを使用して多くのクレイジーなことを行うことができます。 これがドキュメントです。

ボーナスラウンド

[itemprop = articleSection] ul ul li :: before {content:“”; 左:36px; マージントップ:9px; 位置:絶対; border-top:6pxソリッド透明; border-bottom:6pxソリッド透明; border-left:4px solid#EFBB35; border-top:4px solid#EFBB35; border-bottom:4px solid#EFBB35; border-right:4px solid#EFBB35; } [itemprop = articleSection] ul ul li、[itemprop = articleSection] ul ul li code {font-size:1rem; }

モバイルバージョンを終了