Mobile Reality is attending New York FinTech Week | Let's meet with our CEO in NYC! 8-11th April
BOOK MEETING

Web Development5 practical use cases of Vue JS in Web Development

The Vue philosophy is about providing the simplest possible API for creating real-time two-way data binding between a view and a model.
Updated at14.03.2024
Published at13.04.2022
Magda Dembna
Magda Dembna

Frontend & Mobile Team Leader

Stanislav Naborshchikov
Stanislav Naborshchikov

Solutions Specialist

Table of contents

  1. Introduction
  2. Navigation menu
  3. Built-in editor
  4. Order form
  5. Instant search
  6. Switchable grid
  7. Conclusion 
  8. Frontend Development Insights: Mastering ReactJS and VueJS

Share the article

Introduction

The Vue philosophy is about providing the simplest possible API for creating a real-time two-way data binding between a view (HTML template) and a model (JavaScript object).

The easiest way to install Vue JS is just attach it with the <script> tag to the end of the HTML document. The entire library is contained in a single js file, which can be downloaded from the official website or imported directly via CDN:

If you want to use Node, Vue is available as an npm module. The module has its interface in the terminal for flexible project configuration.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.5/vue.min.js"></script>

Below are five examples of using Vue.js with links to live demos with code and comments.

Navigation menu

Let's build a simple navigation bar. There are a few basic components that all Vue-based applications should have.

Model

This is essentially the application's data layer. In Vue JS, the model is represented by a JavaScript object that contains data properties. These properties are reactive, meaning VueJS will automatically update the view whenever these data properties change. This reactivity makes it easy to manage the state of your navigation menu, such as highlighting the active page or dynamically updating menu items based on user roles or permissions. Here's an example of a navigation menu:

data() {
    return {
        menuItems: [
            { title: 'Home', link: '/' },
            { title: 'About', link: '/about' },
            { title: 'Contact', link: '/contact' }
        ],
        activeItem: 'Home'
    };
}

View

This is the HTML template where your data is displayed. Vue JS uses a declarative approach, allowing you to bind the DOM to the underlying model's data. For a navigation menu, this could mean using Vue JS directives to loop through a list of menu items, conditionally rendering elements based on user interaction, or displaying different menu styles based on the current route. For a navigation menu, you might have:

<nav>
    <ul>
        <li v-for="item in menuItems" 
            :class="{ active: item.title === activeItem }" 
            @click="setActive(item.title)">
            {{ item.title }}
        </li>
    </ul>
</nav>

ViewModel

In Vue JS, this acts as a mediator between the Model and the View. The ViewModel in Vue JS is an instance of the Vue class. It's where you define data properties, computed properties, methods, and lifecycle hooks. It's also where you handle events like clicks on menu items. The ViewModel ensures that the View reflects the state of the Model, and any changes made in the View are propagated back to the Model. For our menu:

methods: {
    setActive(itemTitle) {
        this.activeItem = itemTitle;
    }
}

Vue JS simplifies the interaction between these components with its intuitive and powerful features:

  • Simple JavaScript Object for Options: Vue.js uses a plain JavaScript object to define the ViewModel, making the code more readable and easier to understand.

  • Text Interpolation with Double Braces ({{ }}): This feature allows you to display dynamic data in your HTML templates easily. In the case of a navigation menu, you can use text interpolation to display labels for menu items.

  • Built-in Directives: Vue.js provides a range of built-in directives, such as v-for for rendering lists (useful for generating menu items), v-if/v-show for conditionally displaying elements (like showing/hiding menu items based on conditions), and v-bind for dynamically binding HTML attributes.

  • Event Handling with v-on: This directive allows you to listen to DOM events and execute some JavaScript when they occur. For instance, you can use v-on:click to define what happens when a user clicks a menu item.

  • Vue Router for Navigation: Integrating Vue Router with your navigation menu allows for seamless navigation in single-page applications (SPAs). You can define routes and update the navigation menu based on the current route, enhancing user experience with features like lazy-loading of route components or nested routes.

In summary, Vue JS provides a rich set of tools and features that make building a responsive and interactive navigation menu straightforward and efficient. By leveraging the Model-View-ViewModel architecture, Vue.js allows developers to create complex navigation structures with minimal code while maintaining high performance and reactivity.

Built-in editor

Vue JS simplifies creating interactive, data-driven applications like a built-in text editor. This is primarily achieved through two-way data binding, which ensures that changes in the user interface instantly update the data model and vice versa. Here's how it works in Vue JS:

1. Two-Way Data Binding with v-model: This directive creates a two-way binding on an input, textarea, or select element. When the input value changes, the data property it's bound to updates automatically.

For example, if you have a text editor where users can input text, the setup would be:

<textarea v-model="textContent"></textarea>

And in your Vue instance:

data() {
    return {
        textContent: 'Enter your text here'
    };
}

2. Reactivity: Any change made in the textarea will be immediately reflected in the textContent property of your Vue instance. Likewise, any changes to textContent will automatically update the content in the textarea.

3. Conditional Rendering with v-if: This directive allows you to conditionally render elements based on the truthiness of an expression. It's extremely useful for showing or hiding parts of your interface in response to user interaction or other conditions.

For example, you might want to show a preview of the text content:

<div v-if="textContent">
    Preview: <span>{{ textContent }}</span>
</div>

Here, the div element will only be displayed if textContent contains some text.

4. Example Scenario: Let's say we want to create a simple text editor where users can write text, and a preview of their text is shown only when they've written something. The setup would look like this:

<template>
    <textarea v-model="textContent" placeholder="Write something..."></textarea>
    <div v-if="textContent">
        Preview: <span>{{ spanText }}</span>
    </div>
</template>

<script>
export default {
    data() {
        return {
            textContent: ''
        };
    },
    computed: {
        spanText() {
            // You can add additional logic here if needed
            return this.textContent;
        }
    }
};
</script>


In this example, the v-model directive binds the textarea to the textContent property. The v-if directive checks if textContent is not empty to display the preview. The spanText computed property is used here to demonstrate how you might process or format the text content before displaying it.

Through these features, VueJS makes it straightforward to create a responsive and interactive text editor with minimal code, demonstrating the power and simplicity of the Vue JS framework for handling dynamic user interfaces.

Order form

Vue.js excels in creating interactive forms such as an order form, where users can select from a list of services and see the total cost updated in real-time. Here's how you can implement this with Vue.js:

1. Displaying Services with v-for: The v-for directive is perfect for iterating over an array of services and displaying them in the form. Each service can include details like name and price.

<div v-for="service in services" :key="service.id">
    <input type="checkbox" :value="service" v-model="selectedServices">
    {{ service.name }} - {{ service.price | currency }}
</div>

2. Reactivity: Vue.js will automatically update the view if any changes are made to the services array. This is particularly useful when dealing with dynamic data where services might be added, removed, or updated.

3. Currency Filter: Filters in Vue.js are used to apply common text formatting. A simple currency filter can format the price.

filters: {
    currency(value) {
        return `$${value.toFixed(2)}`;
    }
}

4. Calculating Total Cost: You can use a computed property to calculate the total cost of the selected services.

computed: {
    totalCost() {
        return this.selectedServices.reduce((total, service) => {
            return total + service.price;
        }, 0);
    }
}


5. Example Scenario: Let's create an order form where users can select services and see the total cost:

<template>
    <div v-for="service in services" :key="service.id">
        <input type="checkbox" :value="service" v-model="selectedServices">
        {{ service.name }} - {{ service.price | currency }}
    </div>
    <div>Total Cost: {{ totalCost | currency }}</div>
</template>

<script>
export default {
    data() {
        return {
            services: [
                { id: 1, name: 'Web Design', price: 300 },
                { id: 2, name: 'SEO Optimization', price: 200 },
                { id: 3, name: 'Digital Marketing', price: 250 }
            ],
            selectedServices: []
        };
    },
    computed: {
        totalCost() {
            return this.selectedServices.reduce((total, service) => {
                return total + service.price;
            }, 0);
        }
    },
    filters: {
        currency(value) {
            return `$${value.toFixed(2)}`;
        }
    }
};
</script>


In this example, v-for is used to render each service as a checkbox. The v-model checkbox creates a two-way binding with the selectedServices array. The currency filter formats the service prices and total cost. The totalCost computed property calculates the sum of the prices of the selected services.

This example highlights Vue's ability to handle dynamic data and user interactions in an efficient and reactive way, making it an excellent choice for building forms and other interactive web elements.

Vue JS is highly effective for building features like an instant search, where user input dynamically filters data - in this case, articles. Here's how you can implement an instant search functionality in VueJS:

1. Data Binding with v-model: We'll use v-model to create a two-way binding on the search input field. This ensures that the value entered in the input field is reflected in the Vue instance's data property in real-time.

<input type="text" v-model="searchString" placeholder="Search articles">

2. Reactive Search: As searchString is updated, Vue.js automatically triggers updates in the view. This reactive behavior is key to creating an instant search feature.

3. Filtering Articles: We'll use a computed property to filter the articles based on the search query. This property will return a filtered array of articles that match the search string.

computed: {
    filteredArticles() {
        return this.articles.filter(article => 
            article.title.toLowerCase().includes(this.searchString.toLowerCase())
        );
    }
}

4. Example Scenario: Let's create an application that includes a list of articles and a search box to filter them:

<template>
    <input type="text" v-model="searchString" placeholder="Search articles">
    <ul>
        <li v-for="article in filteredArticles" :key="article.id">
            {{ article.title }}
        </li>
    </ul>
</template>

<script>
export default {
    data() {
        return {
            searchString: '',
            articles: [
                { id: 1, title: 'Introduction to Vue.js' },
                { id: 2, title: 'Vue.js Components Explained' },
                { id: 3, title: 'Advanced Vue.js Tips' }
                // ... other articles
            ]
        };
    },
    computed: {
        filteredArticles() {
            return this.articles.filter(article => 
                article.title.toLowerCase().includes(this.searchString.toLowerCase())
            );
        }
    }
};
</script>

In this example, the searchString is bound to the input field. The filteredArticles computed property dynamically filters the articles array based on the search string. The v-for directive is used to render each filtered article.

This approach demonstrates Vue's ability to handle data reactively and efficiently, making it an ideal choice for building real-time search functionalities. The use of computed properties ensures optimal performance, as they are only re-evaluated when their dependencies change, making VueJS an excellent tool for building responsive and interactive web applications.

Switchable grid

Vue JS is adept at handling dynamic user interfaces, such as a switchable grid layout where users can toggle between different display modes for content. In this example, we'll show how to switch between a grid and a list layout for articles:

1. Toggle for Layout Modes: We'll use a data property to track the current layout mode. Buttons or similar controls can be used to switch between modes.

<button @click="layoutMode = 'grid'">Grid View</button>
<button @click="layoutMode = 'list'">List View</button>

2. Dynamic Class Binding: Vue'sv-bind:class or :class directive can dynamically apply different CSS classes based on the current layout mode, changing the appearance of the article display.

<div :class="{ grid: layoutMode === 'grid', list: layoutMode === 'list' }">
    <!-- Articles will be displayed here -->
</div>

3. Displaying Articles: Depending on the selected layout mode, articles can be displayed with different styles. v-for can be used to iterate over the articles.

4. Example Scenario: Let's create a component that includes a list of articles and allows users to switch between a grid and a list layout:

<template>
    <button @click="layoutMode = 'grid'">Grid View</button>
    <button @click="layoutMode = 'list'">List View</button>

    <div :class="{ grid: layoutMode === 'grid', list: layoutMode === 'list' }">
        <div v-for="article in articles" :key="article.id">
            <img :src="article.imageUrl" :alt="article.title">
            <h3>{{ article.title }}</h3>
            <p>{{ article.summary }}</p>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            layoutMode: 'grid', // default layout mode
            articles: [
                // Array of article objects with id, title, imageUrl, and summary
                // Example: { id: 1, title: 'Vue.js Tips', imageUrl: 'path/to/image.jpg', summary: 'Article summary...' }
            ]
        };
    }
};
</script>

In this example, the layoutMode data property is used to switch between 'grid' and 'list' layouts. Buttons are used to toggle this property. The main container's class is dynamically set based on layoutMode, affecting the display style of the articles.

This implementation showcases Vue's flexibility in managing dynamic layouts and user interactions. By combining data-binding, conditional rendering, and class binding, Vue.js makes it straightforward to create complex, interactive UI patterns like a switchable grid layout.

Conclusion 

Throughout this article, "5 Practical Use Cases of Vue JS," we have explored various scenarios where Vue, a progressive JavaScript framework, simplifies the development of interactive and dynamic web applications. From building a primary navigation menu to creating a sophisticated switchable grid layout, VueJS demonstrates its versatility and efficiency.

Key takeaways from the article include:

  1. Ease of Use: Vue offers a straightforward approach to building web applications, making it accessible to beginners while also powerful enough for advanced developers.

  2. Reactivity and Data Binding: With features like two-way data binding and reactive data properties, Vue ensures seamless synchronization between the user interface and the application state.

  3. Modularity and Flexibility: Vue's component-based architecture allows for the creation of reusable and maintainable code, making it ideal for both small and large-scale projects.

  4. Dynamic User Interfaces: The examples showcased VueJS's capability to handle dynamic content and user interactions effectively, such as in instant search features and switchable layouts.

  5. Customizability and Extensibility: Vue JS provides a range of customization options, from simple filters for text formatting to integration with various plugins and external libraries, enhancing its functionality.

In conclusion, Vue stands out as a powerful tool in the web developer's arsenal. Its simplicity, coupled with its robust feature set, makes it a go-to choice for a wide range of web applications. Whether it's a simple form or a complex interactive application, Vue.js provides the necessary tools and flexibility to build high-quality, interactive, and responsive web applications efficiently. As the web development landscape continues to evolve, Vue.js remains a relevant and valuable framework for tackling the diverse challenges of modern web application development.

Frontend Development Insights: Mastering ReactJS and VueJS

Are you fascinated by the evolving landscape of frontend development, particularly in ReactJS and VueJS? At Mobile Reality, we are eager to share our rich expertise and insights in these cutting-edge technologies. Uncover the challenges we navigate, the innovative strategies we employ, and the groundbreaking solutions we deliver in ReactJS and VueJS development. Immerse yourself in our curated selection of articles, each a deep dive into aspects of these powerful frontend frameworks:

Delve into these comprehensive resources to enhance your understanding of ReactJS and VueJS. For any inquiries or if you’re considering a career with us, don't hesitate to contact us or visit our careers page to submit your CV. Join us in shaping the future of front-end development!

Did you like the article?Find out how we can help you.

Matt Sadowski

CEO of Mobile Reality

CEO of Mobile Reality

Related articles

Discover the essential guide for CTOs comparing Node JS vs PHP. Make the right choice for your tech stack. Get insights now! #nodejs #php #CTO

26.03.2024

Node JS vs PHP: A Complete Comparison for CTOs

Discover the essential guide for CTOs comparing Node JS vs PHP. Make the right choice for your tech stack. Get insights now! #nodejs #php #CTO

Read full article

Read what types of applications you can build using Node JS technology.

26.03.2024

Types of Apps You Can Build with Node JS in 2024

Read what types of applications you can build using Node JS technology.

Read full article

Hydration in SSR with React 18's

26.03.2024

Understanding Hydration in SSR with React 18's New Architecture

Hydration in SSR with React 18's

Read full article