Cours Vue.js · Module 14: Directives et plugins

Hooks des directives - arguments, modificateurs, valeurs

2 min de lecture ·
Dans cette leçon6

Au Centre de commandement de NOVA LAB, chaque système exige des paramètres précis. Les directives Vue offrent un riche ensemble de données à travers l'objet binding.

L'objet binding

Chaque hook de directive reçoit deux paramètres principaux : el (l'élément du DOM) et binding (un objet contenant des données) :

app.directive('demo', {
  mounted(el, binding) {
    // binding.value    - la valeur passée : v-demo="123" => 123
    // binding.arg      - l'argument : v-demo:color => 'color'
    // binding.modifiers - les modificateurs : v-demo.bold => { bold: true }
    // binding.oldValue - la valeur précédente (dans updated)
  }
})

Valeur de la directive : binding.value

La valeur est l'expression JavaScript passée après = :

<template>
  <div v-color="'#00ff88'">Texte vert</div>
  <div v-color="themeColor">Couleur dynamique</div>
  <div v-color="{ bg: '#0a0e27', text: '#00ff88' }">Objet</div>
</template>
app.directive('color', (el, binding) => {
  if (typeof binding.value === 'string') {
    el.style.color = binding.value
  } else {
    el.style.backgroundColor = binding.value.bg
    el.style.color = binding.value.text
  }
})

Arguments : binding.arg

L'argument est la partie qui suit les deux-points - il te permet de préciser ce que la directive doit modifier :

<template>
  <div v-style:color="'#00ff88'">Couleur du texte</div>
  <div v-style:backgroundColor="'#0a0e27'">Couleur de fond</div>
  <div v-style:fontSize="'20px'">Taille de police</div>
</template>
app.directive('style', (el, binding) => {
  if (binding.arg) {
    el.style[binding.arg] = binding.value
  }
})

Arguments dynamiques

L'argument peut être dynamique - utilise des crochets :

<script setup>
import { ref } from 'vue'
const prop = ref('color')
</script>

<template>
  <div v-style:[prop]="'#00ff88'">Attribut dynamique</div>
</template>

Modificateurs : binding.modifiers

Les modificateurs sont des drapeaux booléens placés après un point :

<template>
  <p v-format.bold.uppercase>nova lab station</p>
</template>
app.directive('format', (el, binding) => {
  if (binding.modifiers.bold) {
    el.style.fontWeight = 'bold'
  }
  if (binding.modifiers.uppercase) {
    el.textContent = el.textContent.toUpperCase()
  }
  if (binding.modifiers.italic) {
    el.style.fontStyle = 'italic'
  }
})

Tout mettre ensemble

Syntaxe complète d'une directive :

v-name:argument.modifier1.modifier2="value"

Exemple :

<div v-tooltip:top.slow="'Station information'">
  Survole-moi
</div>

Où :

  • tooltip - nom de la directive
  • top - argument (position)
  • slow - modificateur (animation)
  • 'Station information' - valeur (texte)
Code de cette leçon : App.vue
<script setup>
import { ref } from 'vue'

// Directive avec binding.arg
const vStyle = (el, binding) => {
  if (binding.arg) {
    el.style[binding.arg] = binding.value
  }
}

// Directive avec binding.modifiers
const vFormat = (el, binding) => {
  let text = el.textContent
  if (binding.modifiers.uppercase) {
    text = text.toUpperCase()
  }
  if (binding.modifiers.lowercase) {
    text = text.toLowerCase()
  }
  el.textContent = text
  if (binding.modifiers.bold) {
    el.style.fontWeight = 'bold'
  }
  if (binding.modifiers.italic) {
    el.style.fontStyle = 'italic'
  }
}

// Directive combinant tout
const vPanel = {
  mounted(el, binding) {
    const color = binding.value || '#00ff88'
    const size = binding.arg || 'md'
    const paddings = { sm: '8px', md: '16px', lg: '24px' }

    el.style.border = '2px solid ' + color
    el.style.padding = paddings[size] || paddings.md
    el.style.borderRadius = '8px'

    if (binding.modifiers.glow) {
      el.style.boxShadow = '0 0 15px ' + color + '40'
    }
    if (binding.modifiers.dashed) {
      el.style.borderStyle = 'dashed'
    }
  }
}

const dynamicProp = ref('color')
</script>

<template>
  <div class="nova-lab">
    <h1>Directive Hooks - Args & Modifiers</h1>

    <section class="section">
      <h2>binding.arg (v-style:property)</h2>
      <p v-style:color="'#00ff88'">Couleur verte</p>
      <p v-style:fontSize="'20px'">Police plus grande</p>
      <p v-style:backgroundColor="'rgba(0, 180, 216, 0.2)'">Fond cyan</p>
    </section>

    <section class="section">
      <h2>binding.modifiers (v-format.bold.uppercase)</h2>
      <p v-format.uppercase>station nova lab</p>
      <p v-format.bold.italic>message important</p>
      <p v-format.uppercase.bold>red alert</p>
    </section>

    <section class="section">
      <h2>Tout ensemble : v-panel</h2>
      <div v-panel:md.glow="'#00ff88'" style="margin-bottom: 10px">
        <p>v-panel:md.glow="#00ff88"</p>
      </div>
      <div v-panel:lg.dashed="'#00b4d8'" style="margin-bottom: 10px">
        <p>v-panel:lg.dashed="#00b4d8"</p>
      </div>
      <div v-panel:sm.glow.dashed="'#e74c3c'">
        <p>v-panel:sm.glow.dashed="#e74c3c"</p>
      </div>
    </section>

    <section class="section">
      <h2>Argument dynamique : v-style:[prop]</h2>
      <select v-model="dynamicProp" class="select">
        <option value="color">color</option>
        <option value="fontSize">fontSize</option>
        <option value="backgroundColor">backgroundColor</option>
      </select>
      <p v-style:[dynamicProp]="dynamicProp === 'fontSize' ? '22px' : dynamicProp === 'backgroundColor' ? 'rgba(0,255,136,0.2)' : '#00b4d8'" style="margin-top: 8px">
        Le texte change dynamiquement
      </p>
    </section>
  </div>
</template>

<style scoped>
.nova-lab {
  background: #0a0e27;
  color: #c0c0c0;
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 20px; }
h2 { color: #00b4d8; font-size: 16px; margin-bottom: 10px; }
.section {
  background: rgba(0, 180, 216, 0.05);
  border: 1px solid rgba(0, 180, 216, 0.2);
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
}
.select {
  background: #0a0e27;
  color: #00ff88;
  border: 1px solid #00ff88;
  padding: 8px;
  border-radius: 4px;
  font-family: monospace;
}
</style>

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Que contient binding.value dans la directive v-demo="123" ?

  2. 2. Que renvoie binding.arg dans la directive v-style:color="'red'" ?

Voici 2 des 3 questions de cette leçon. Réponds aux autres dans le jeu.

Tâches pratiques dans le jeu

  • Éditeur de code

    Utilise binding.arg comme nom de propriété CSS et binding.value comme valeur.

  • Tri horizontal

    Ordonne la syntaxe correcte d'une directive avec un argument et une valeur :

  • Éditeur de code

    Vérifie binding.modifiers.bold, binding.modifiers.uppercase et binding.modifiers.italic.

  1. QuestionL'objet binding.value
  2. QuestionArgument d'une directive
  3. Exercice de codePratique : directive avec argument
  4. Remets dans l'ordreSyntaxe d'une directive avec argument
  5. QuestionModificateurs d'une directive
  6. Exercice de codePratique : directive avec modificateurs

Articles utiles