# VueJS basic syntax

## What is VueJS

> Vue (pronounced /vjuː/, like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries

{% embed url="<https://www.youtube.com/watch?v=nhBVL41-_Cw&ab_channel=Fireship>" %}
Vue in 100 seconds
{% endembed %}

## Comparison with other frameworks

1. Virtual DOM
2. Declarative rendering
3. Reactive
4. Single-page components
5. Small footprint

{% embed url="<https://www.geeksforgeeks.org/difference-between-virtual-dom-and-real-dom/>" %}
More on the concept of Virtual DOM
{% endembed %}

**The virtual DOM** is a lightweight representation of the real DOM (Document Object Model). It is used by some JavaScript frameworks, such as React, Vue.js, and Elm, to efficiently update the UI of a web application.

The VDOM is a tree-like structure that represents the UI of the application. Each node in the VDOM tree represents a DOM element. The VDOM tree is updated whenever the state of the application changes.

When the VDOM tree is updated, the framework compares the old VDOM tree to the new VDOM tree. The framework then calculates the minimal set of changes that need to be made to the real DOM to reflect the changes in the VDOM tree.

The framework then makes those changes to the real DOM. This process is called reconciliation.

Reconciliation is much faster than updating the real DOM directly because the framework only needs to make the minimal set of changes necessary. This makes VDOM-based frameworks very efficient at updating the UI of a web application.

**Declarative rendering** is a programming paradigm that focuses on describing what the UI should look like, rather than how to update the UI. This makes declarative rendering much easier to read and maintain than imperative rendering, which focuses on how to update the UI.

Declarative rendering is often used in combination with the virtual DOM to efficiently update the UI of a web application.

**Reactive programming** is programming with async data streams. A stream is a sequence of ongoing events ordered in time that offer some hooks with which to observe with. When we use reactive premises for building apps, this means it's very easy to update state in reaction to events.

Reactivity example in a CalcSheet app.

|   | A | B             | C | D |
| - | - | ------------- | - | - |
| 1 | 3 |               |   |   |
| 2 | 4 |               |   |   |
| 3 | 7 | '=SUM(A1:A2)' |   |   |

Lack of reactivity in plain JavaScript:

```javascript
let a = 5
let b = 8
let c = a + b

console.log(c) //13

a = 10

console.log(c) //still 13
```

Vue.js is not actually a reactive programming framework. However, **Vue.js does implement some reactive programming concepts**, such as two-way data binding and change detection.

Two-way data binding allows Vue.js to automatically update the UI when the state of the application changes. Change detection allows Vue.js to identify which parts of the UI need to be updated when the state of the application changes.

This makes Vue.js very efficient at updating the UI, especially when compared to traditional imperative programming approaches.

### V3 vs V2

Almost the same interface API and syntax.

Different reactivity implementation (it uses Proxies vs. Object.defineProperty)

It has its code split in packages (it results in smaller builds if you don't use certain sections such as animations for instance)

The Composition API.

### Installation and usage

1. **embedded as a script, usually CDN:** used for less complex applications, study purposes, or for instance if you want to replace jQuery.
2. **"buildable" applications through a dedicated CLI (Command Line Interface).** This is designed for large-scale applications and structured code-bases.

## The Vue Instance

Vue Instance is the central object that manages a part of your application's UI. It's created using the `new Vue()` constructor, and it's the starting point for Vue to take control of a section of your DOM and make it reactive and dynamic.

```javascript
const vm = new Vue({
  // options object goes here
});
```

The options object may contain the following sections, *which will be detailed later on*:

* **`data`: Reactive Data.** This is where you define the data that your Vue Instance will manage and track for changes. Vue's reactivity system is built around the data option. When you access data properties in your template or methods, Vue automatically tracks these dependencies and updates the DOM when the data changes.&#x20;
* **`methods`: Functions.** You define methods here to encapsulate logic that your Vue Instance needs to perform. These methods can be called from your templates (e.g., in event handlers) or from other methods within the instance. `this` inside methods automatically binds to the Vue Instance itself.
* **`computed`:** **Computed Properties.** Computed properties are functions that are cached based on their dependencies. They are used to derive data from existing data properties. Computed properties are only re-evaluated when their dependencies change, making them efficient for complex calculations or data transformations that you need to access frequently.
* **`watch`:** **Watchers.** Watchers allow you to react to changes in specific data properties. They are useful for performing side effects when data changes, such as making API calls, logging, or triggering animations.
* **`template` or `render`:** **Defining the View.** These options define the HTML structure that the Vue Instance will manage.
* **`el`:** **Element Binding (Mounting Point).** The `el` option tells Vue where in the existing DOM to mount this instance. It accepts a CSS selector or an actual DOM element. Vue will replace the element with its template (or render function output).
* **Lifecycle Hooks:** These are special methods that are called at different stages of a Vue Instance's lifecycle. They allow you to hook into these stages and perform actions, like fetching data when the component is created, or cleaning up resources when it's destroyed.

## Hello world! example

Here is an alternative method to create a root instance and mount it to a DOM element. `HelloWorld` is a **Vue component definition**.

{% tabs %}
{% tab title="script.js" %}

```javascript
const HelloWorld = {
    data() {
      return {
        message: 'Hello World!'
      }
    }
  }
  
  Vue.createApp(HelloWorld).mount('#hello-world')
```

{% endtab %}

{% tab title="HTML" %}

```javascript
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Vue intro</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
</head>
<body>
    <div id="hello-world" class="demo">
        {{ message }}
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src='script.js'></script>
</body>
</html>
```

{% endtab %}
{% endtabs %}

## Basic directives

### v-if / v-else

These are paired (`v-else` is optional) directives used for **conditional rendering.** The DOM elements are inserted when the conditions are fulfilled.

{% tabs %}
{% tab title="script.js" %}

```javascript
const app = {
    data() {
      return {
        condition: false,
        success: 'The condition is true',
        fail: 'The condition is false'
      }
    }
  }
  
  Vue.createApp(app).mount('#app')
```

{% endtab %}

{% tab title="HTML" %}

```javascript
//...
<div id="app" class="demo">
    <p v-if=condition>
        {{ success }}
    </p>
    <p v-else>
        {{ fail }}
    </p>
</div>
//...
```

{% endtab %}
{% endtabs %}

### v-show

`v-show` is also used for **conditional rendering,** the main difference between it and `v-if` is that the DOM elements are inserted from the beginning and there is a `display: none` property in case the condition is not true.

### v-for

This is a directive used for rendering lists. You can easily remark how declarative it is.

{% tabs %}
{% tab title="script.js" %}

```javascript
const app = {
    data() {
      return {
        iterable: [4, 9, 2]
      }
    }
  }
  
  Vue.createApp(app).mount('#app')
```

{% endtab %}

{% tab title="HTML" %}

```javascript
//...
<div id="app" class="demo">
    <p v-for="(el, index) in iterable">
        The value is {{ el }}.
        It has the index of {{ index }} from a total of {{ iterable.length }}
    </p>
</div>
//...
```

{% endtab %}
{% endtabs %}

### v-bind

`v-bind:` or it's shorthand `:` is used for one way binding between some data or evaluation of an expression and an attribute of an element.

In the following example, we are binding the button's class to a ternary operator that evaluates `isActive` from Vue instance data.

```javascript
//...
<button :class="isActive ? activeClass : inactiveClass"></button>
//shorthand for v-bind:
//...
```

### v-model

Is used for two-way binding between user input and other data / elements.

{% tabs %}
{% tab title="HTML" %}

```javascript
//...
<div id="app" class="demo">
    <p>{{ counter }}</p>
    <input v-model="counter" />
    <button @click="increment">Click me!</button> //@ is the shorthand for v-on:
</div>
//...
```

{% endtab %}

{% tab title="script.js" %}

```javascript
const app = {
    data() {
      return {
        counter: 0
      }
    },
    methods: {
        increment() {
            this.counter++
        }
    }
  }
  
  Vue.createApp(app).mount('#app')
```

{% endtab %}
{% endtabs %}

### v-on

Used to trigger an action in case of an event such as click or keypress.

```javascript
//mouse events
<div 
  @mousedown='handleEvent'
  @mouseup='handleEvent'
  @click='handleEvent'
  @dblclick='handleEvent'
  @mousemove='handleEvent'
  @mouseover='handleEvent'
  @mousewheel='handleEvent'
  @mouseout='handleEvent'
>
Interact with Me!
</div>

//key events
<input
   type='text'
   placeholder='Type something'
   @keypress='handkeKeyPressed'
   @keydown='handleKeyDown'
   @keyup='handleKeyUp'
/>
```

## Modifiers

Examples:

`v-model.trim` strips any leading or trailing whitespace.

`v-model.number` changes strings to number inputs.

`@submit.prevent` this will no longer reload the page on submission

## Methods

Similar to functions. They have access to the data object. They should be used for changing data and are usually triggered by events.

{% tabs %}
{% tab title="script.js" %}

<pre class="language-javascript"><code class="lang-javascript"><strong>const app = {
</strong>    data() {
      return {
        amount: 50,
        cost: 0
      }
    },
    methods: {
        addToAmount(cost) {
            this.amount+=cost
        }
    },
    computed: {
        tax() {
            return (this.amount*.2).toFixed(2)
        }
    },
    watch: {
        amount(newValue, oldValue) {//optional parameters
            console.log(`The old amount of ${oldValue} has changed
            with this one: ${newValue}`)
        }
    }
  }
  
  Vue.createApp(app).mount('#app')
</code></pre>

{% endtab %}

{% tab title="HTML" %}

```javascript
//...
<div id="app" class="demo">
    <p>The Amount to be paid is {{ amount }} with a tax of {{ tax }}</p>
    <input v-model.number="cost" />
    <button @click="addToAmount(cost)">Add</button>
</div>
//...
```

{% endtab %}
{% endtabs %}

## Computed properties

Somehow similar to methods but re-render only when the data dependency is changed. They are useful for different perspectives on the existing data, for instance, filters.

They are very powerful because the results are cached which translates into better performance.

## Watchers

Good for async updates and tracking changes.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://mihai-gheorghe.gitbook.io/tic/vuejs-basic-syntax.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
