1. Displaying dynamic text

  • Use "mustaches" {{ }} in the template to display JavaScript expressions.
  • Can contain a variable name, a function call, or a simple statement (without if/for/while).
  • Logical and arithmetic operators are allowed.
  • Warning: {{ }} does not add elements to the DOM; the HTML is displayed literally, not interpreted.
  • Use the v-html attribute to interpret the HTML content of a data variable.
General remarks:
  • NEVER use v-html with values coming from user input (security vulnerability).
  • Only data variables are accessible; not external variables.

2. One-way data binding: v-bind

  • Mustaches do not work for attributes. The solution is to bind the value of an attribute to a variable = data binding. One-way means that modifying the variable modifies the value of the attribute but not the opposite.
  • Use v-bind:attribute_name="js_expression".
  • The expression follows the same principles as {{ }}.
  • The returned type must match the expected type:
    • Booleans for attributes such as readonly.
    • Objects/arrays for style.
    • Objects/arrays for class.
  • Shorthand: remove v-bind and keep the : before the attribute name.
Remark: v-bind works on HTML attributes and on component attributes (to pass props).

 

3. Two-way data binding: v-model

  • Establishes a two-way synchronization between a data field and an HTML element.
  • Applies to <input> tags (text, radio, checkbox) and <select>.
  • User changes update the data variable.

 

4. Displaying lists: v-for

  • Iterates over an array or object to repeat tags with different values.
  • Main syntaxes:
    • v-for="el in tab": iterates over each element.
    • v-for="(el, idx) in tab": adds the index.
    • v-for="(val, name, idx) in obj": for objects.
  • Important: assign a unique key with the key attribute (often the index).
  • Reduces code redundancy, particularly useful for large lists.
Remarks:
  • You can nest several v-for.
  • Works together with v-bind.
  • Applies to HTML tags and components.

 

5. Conditional display: v-if, v-else-if, v-else

  • Creates or removes elements from the DOM depending on a condition.
  • v-if and v-else-if take a JavaScript expression.
  • v-else has no parameter.
  • Applies only to the tag carrying the directive.
  • To make the condition apply to several nested tags: use a <div> or a <template>.