Vue is a progressive JavaScript framwork designed for building user interfaces. It adopts a declarative and component-based architecture, enabling developers to create responsive and maintainable front-end applications with simplicity and efficiency.
Getting Started with Vue 3
1. Including Vue in Your Project
To begin, fetch Vue 3 from the official CDN:
https://unpkg.com/vue@3/dist/vue.global.js
Right-click the page and choose "Save As" to download the script file. You may rename it—for instance, to vue.js—for convenience.
2. First Application
Below is a minimal example demonstrating core Vue instantiation and raectivity:
Core Vue Syntax
1. Interpolation
Use double curly braces to embed reactive data into templates:
<p>{{ message }}</p>
Vue replaces {{ message }} with the value of the message property from data().
2. Attribute Binding with v-bind
Since interpolation doesn’t work in HTML attributes, use v-bind (or its shorthand :).
</div>Result: The `<div>` gains `id="banner"` and `class="highlight"` dynamically.
### 3. Dynamic `class` and `style` Binding
**Class Binding Options:**
- **String:** `<div :class="activeClass">`
- **Object:** `<div :class="{ active: isActive, muted: isDisabled }">`
- **Array:** `<div :class="['base', error ? 'error' : '']">`
**Style Binding Options:**
- **Object:** `<div :style="{ color: textColor, fontSize: textSize + 'px' }">`
- Use camelCase or quoted kebab-case keys: ``'background-color'``.
### 4. Text Rendering Directives
- `v-text`: Inserts plain text only.
- `v-html`: Renders raw HTML content (use cautiously for security).
<div class="highlight">```
<p v-text="content" ></p>
<p v-html="content" ></p>
// data()
content: '<em>Formatted Text</em>'
v-iftoggles DOM presence. Renders only when truthy; otherwise removes the element entire. Works with<template>and supportsv-else-if/v-else.v-showtoggles visibility viadisplay: none. Remains in the DOM and is better suited for frequent toggling.
6. List Rendering with v-for
Iterate over arrays or objects:
// data() names: ['Sam', 'Alex', 'Jules'],
// For objects:
Bind form inputs directly to state:
- Single: Binds to a Boolean.
- Multiple: Binds to an array (Docs).
Select Binding:
- Single select: Bound to a string/number.
- Multiple select: Bound to an array (add
multipleattribute).
Modifiers:
.lazy: Sync onchangeinstead ofinput..number: Auto-converts input to numbers..trim: Removes leading/trailing whitespace.
Example: <input v-model.trim="name" />
Vue ignores initial HTML attributes like value, checked, or selected; it uses the JavaScript data state as the single source of truth. Initialize defaults in data().