Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Getting Started with Vue.js: Core Concepts and Directives

Tech 1

Architecture Overview

Vue.js is a progressive JavaScript framework focused on building user interfaces and single-page applications. It adopts a component-based architecture, promoting reusable and maintainable code by composing self-contained units. The library adheres to the principle of separation of concerns, primarily dealing with the view layer—combining HTML, CSS, and JavaScript—to render data and respond to user interactions.

The MVVM Pattern

Vue embraces the Model-View-ViewModel (MVVM) design pattern, an evolution of the classic Model-View-Controller (MVC) approach. This pattern decouples the graphical interface from the business logic and data.

  • Model: Represents the application's data and business rules. It typically synchronizes with a backend service via APIs.
  • View: The visible template that defines structure and layout. It declaratively binds to the state exposed by the ViewModel and never handles logic directly.
  • ViewModel: Serves as a bridge between the Model and the View. It exposes processed data, handles user input, and manages display logic. Vue's reactivity system ensures that changes in the ViewModel automatically update the View, and vice versa for two-way bound inputs.

Key Instance Options

A Vue instance accepts several important configuration options:

  • el: A CSS selector string that specifies the root DOM element for the Vue instance.
  • data: An object or function that holds the reactive state consumed by the template.
  • methods: Contains functions that implement application logic and event handlers.
  • template: A string representing the HTML template to render.
  • render: An alternative to templates for creating Virtual DOM nodes programmatically.
  • computed: Defines cached, derived values that automatically update when thier dependencies change.
  • watch: Observes specific data properties and executes custom logic when values change, providing access to both old and new values.

Mount Point Rules

The element targeted by el acts as the rendering boundary. Vue controls this element and its descendants. You can use ID selectors (#example) or class selectors (.example), but the mount point must be a standard container element and cannot be <html> or <body>.

Fundamental Directives

Directives are special attributes prefixed with v- that apply reactive behavior to the DOM.

One-Time Rendering with v-once

Elements marked with v-once are rendered only once and will not update even if their bound data changes.

<div id="app-container">
  <p>Reactive: {{ description }}</p>
  <p v-once>Static snapshot: {{ description }}</p>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app-container',
    data: {
      description: 'Initial text'
    }
  });
</script>

Text and HTML Binding

Use v-text to set an element's text content, which replaces any existing children. For rendering raw HTML, v-html provides the necessary functionality, though caution with user-supplied content is advised to avoid XSS vulnerabilities.

<div id="display-area">
  <span v-text="rawValue">This will be replaced</span>
  <span v-html="htmlValue"></span>
</div>

<script src="https://cdn.staticfile.org/vue/2.7.0/vue.js"></script>
<script>
  new Vue({
    el: '#display-area',
    data: {
      rawValue: 'Plain content',
      htmlValue: '<strong>Bold rendered content</strong>'
    }
  });
</script>

Attribute Binding with v-bind

v-bind dynamically binds HTML attributes or props to an expression. The shorthand syntax is a colon (:). It can also bind an entire object of attributes.

<div id="binder-demo">
  <header v-bind:title="tooltipInfo">Hover for a tooltip</header>
  <span :class="'prefix-' + suffix">Dynamic class</span>
  <footer v-bind="combinedAttrs">Multiple attributes</footer>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
  new Vue({
    el: '#binder-demo',
    data: {
      tooltipInfo: 'A helpful message',
      suffix: 42,
      combinedAttrs: {
        id: 'secondary-box',
        title: 'Example info',
        class: 'footer-class',
        'data-category': 'extra'
      }
    }
  });
</script>

Conditional Display with v-if, v-else-if, v-else

These directives conditionally render elements based on truthiness of an expression. They completely attach or detach elements from the DOM.

<div id="condition-root">
  <button @click="flipFlag">Toggle Status</button>
  <div v-if="status === 'active'">Active panel</div>
  <div v-else-if="status === 'idle'">Idle panel</div>
  <div v-else>Default panel</div>
</div>

<script src="https://cdn.staticfile.org/vue/2.7.0/vue.min.js"></script>
<script>
  new Vue({
    el: '#condition-root',
    data: {
      status: 'active'
    },
    methods: {
      flipFlag() {
        const states = ['active', 'idle', 'unknown'];
        const currentIdx = states.indexOf(this.status);
        this.status = states[(currentIdx + 1) % states.length];
      }
    }
  });
</script>

Visibility Toggle with v-show

v-show also toggles element visibility based on a condition, but it always keeps the element in the DOM and simply switches its CSS display property. It is more performant for frequent toggles.

<div id="visibility-toggle">
  <p v-show="isVisible">This paragraph is always in the DOM but may be hidden.</p>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
  new Vue({
    el: '#visibility-toggle',
    data: {
      isVisible: true
    }
  });
</script>

List Rendering

The v-for Directive

v-for renders a list of items based on an array or an object. It requires a special syntax in the form of item in items, where items is the source data array. For objects, it iterates over property values.

<ul id="list-container">
  <li v-for="element in arrayData">{{ element }}</li>
  <li v-for="(element, idx) in arrayData">Index {{ idx }}: {{ element }}</li>
  <li v-for="(val, propName, idx) in objectData">{{ propName }}: {{ val }} (Position {{ idx }})</li>
</ul>

<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
  new Vue({
    el: '#list-container',
    data: {
      arrayData: ['Alpha', 'Beta', 'Gamma'],
      objectData: {
        first: 'Entry 1',
        second: 'Entry 2',
        third: 'Entry 3'
      }
    }
  });
</script>
Tags: Vue.js

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.