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 to 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://unpkg.com/vue@3/dist/vue.global.js"></script>
Below are five examples of using Vue.js with links to live demos with code and comments.
Navigation menu in the Vue application
Let’s build a simple navigation bar. There are a few basic file components that all Vue-based applications should have.
Setup
Javascript methods/variables defined here can be accessed from your template. These properties can be easily made reactive (by using `ref()` or` reactive()` wrappers), 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:
<script setup lang="ts"> import { RouterLink, RouterView } from 'vue-router' import {onMounted, ref} from "vue"; const menuItems = [ {title: 'Home', link: '/'}, {title: 'About', link: '/about'}, {title: 'Contact', link: '/contact'} ] const activeItem = ref('Home') const setActiveItem = (value: string) => { activeItem.value = value; } onMounted(() => { console.log(`Component mounted! Active item: ${activeItem.title}`) }) </script>
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>
If you are familiar with a Vue 2 syntax, you will notice a significant difference - in our examples, the object with properties such as data, methods, and life cycle hooks has been replaced with a mixture of variables and functions. This is what we call `Composition API` - it offers several advantages over the `Options API` when it comes to building complex applications.
Template
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:
<template> <header> <nav> <ul> <li :key="index" v-for="(item, index) in menuItems"> <RouterLink :to="item.link" :class="{ active: item.title === activeItem }" @click="setActiveItem(item.title)" > {{ item.title }} </RouterLink> </li> </ul> </nav> </header> <RouterView /> </template>
Vue JS simplifies the interaction between the template and javascript with its intuitive and powerful features:
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. Vue.js allows developers to create complex navigation structures with minimal code while maintaining high performance and reactivity.
Built-in editor as one of Vue examples
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 is bound to update automatically. For example, if you have a text editor where users can input text, the template would be:
<template> <div> <textarea v-model="textContent"></textarea> </div> </template>
And in your setup script:
<script setup lang="ts"> import { ref} from "vue"; const textContent = ref('') </script>
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 render elements based on the truthiness of an expression conditionally. It’s beneficial 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:
<template> <div> <textarea v-model="textContent"></textarea> <p v-if="textContent">Textarea value: {{ textContent }}</p> </div> </template>
Here, the p
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> <div> <textarea v-model="textContent"></textarea> <p v-if="textContent">Textarea value: <span>{{ spanText }}</span></p> </div> </template> <script setup lang="ts"> import {computed, ref} from "vue"; const textContent = ref('') const spanText = computed(() => { // You can add additional logic here if needed return textContent.value; }) </script>
In this example, the v-model
directive binds the textarea
to the textContent
ref. 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.
JavaScript Order form in VueJS
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.
<template> <div> <div v-for="service in services" :key="service.id"> <input type="checkbox" :value="service" v-model="selectedServices"> {{ service.name }} - {{ formatPrice(service.price) }} </div> </div> </template> <script setup lang="ts"> import {computed, ref} from "vue"; const services = [ { id: 1, name: 'Web Design', price: 300 }, { id: 2, name: 'SEO Optimization', price: 200 }, { id: 3, name: 'Digital Marketing', price: 250 } ]; const selectedServices = ref<{ id: number, name: string, price: number }[]>([]); const formatPrice = (value: number) => `$${value.toFixed(2)}` </script>
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. Calculating Total Cost: You can use a computed property to calculate the total cost of the selected services.
const totalCost = computed(() => { return selectedServices.value.reduce((total, service) => { return total + service.price; }, 0); })
4. Example Scenario: Let’s create an order form where users can select services and see the total cost:
<template> <div> <div v-for="service in services" :key="service.id"> <input type="checkbox" :value="service" v-model="selectedServices"> {{ service.name }} - {{ formatPrice(service.price) }} </div> <div>Total Cost: {{ formatPrice(totalCost) }}</div> </div> </template> <script setup lang="ts"> import {computed, ref} from "vue"; const services = [ { id: 1, name: 'Web Design', price: 300 }, { id: 2, name: 'SEO Optimization', price: 200 }, { id: 3, name: 'Digital Marketing', price: 250 } ]; const selectedServices = ref<{ id: number, name: string, price: number }[]>([]); const totalCost = computed(() => { return selectedServices.value.reduce((total, service) => { return total + service.price; }, 0); }) const formatPrice = (value: number) => `$${value.toFixed(2)}` </script>
In this example, v-for
it is used to render each service as a checkbox. The v-model
checkbox creates a two-way binding with the selectedServices
array. 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.
Instant search
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.
<template> <div> <input type="text" v-model="searchString" placeholder="Search articles"> </div> </template> <script setup lang="ts"> import {ref} from "vue"; const searchString = ref(''); </script>
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.
const filteredArticles = computed(() => { return articles.filter(article => article.title.toLowerCase().includes(searchString.value.toLowerCase()) ); })
4. Example Scenario: Let’s create an application that includes a list of articles and a search box to filter them:
<template> <div> <input type="text" v-model="searchString" placeholder="Search articles"> <ul> <li v-for="article in filteredArticles" :key="article.id"> {{ article.title }} </li> </ul> </div> </template> <script setup lang="ts"> import {computed, ref} from "vue"; const articles = [ { id: 1, title: 'Introduction to Vue.js' }, { id: 2, title: 'Vue.js Components Explained' }, { id: 3, title: 'Advanced Vue.js Tips' } // ... other articles ] const searchString = ref(''); const filteredArticles = computed(() => { return articles.filter(article => article.title.toLowerCase().includes(searchString.value.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. Using 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.
Vue Object - 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 = LayoutMode.Grid">Grid View</button> <button @click="layoutMode = 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 === LayoutMode.Grid, list: layoutMode === 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> <div> <button @click="layoutMode = LayoutMode.Grid">Grid View</button> <button @click="layoutMode = LayoutMode.List">List View</button> <div :class="{ grid: layoutMode === LayoutMode.Grid, list: layoutMode === 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> </div> </template> <script setup lang="ts"> import {ref} from "vue"; enum LayoutMode { Grid = 'grid', List = 'list' } const layoutMode = ref(LayoutMode.Grid) const 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, 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:
Ease of Use: Vue offers a straightforward approach to building web applications, making it accessible to beginners and powerful enough for advanced developers.
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.
Modularity and Flexibility: Vue's component-based architecture allows for creating reusable and maintainable code, making it ideal for both small and large-scale projects.
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.
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 is a powerful tool in the web developer's arsenal. Its simplicity and robust feature set make it a go-to choice for a wide range of web applications. Whether a simple form or a complex interactive application, Vue.js provides the 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 web and 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:
- Micro frontend Architecture Guideline
- Pros & Cons of TypeScript In Web Development
- Creating your own streaming app with WebRTC
- A* Pathfinding in React JS Web Development
- Angular vs React JS - Ultimate Comparison
- NextJS Server Side Rendering Framework Guideline
- GatsbyJS: The Ultimate Web Development Guideline
- Progressive Web Apps Development: Guideline for CTOs
- Understanding Hydration in SSR with React 18
- Next JS vs Gatsby: which to choose in 2024
- Deep Dive into Static vs Dynamic Rendering with NextJS
- Web Accessibility in React
- Vue JS vs React – CTO guideline in top frontend frameworks
- Create and publish ReactJS component on npm
- Use Async Actions Hook in ReactJS Web Development
- Web App vs Native App: what's better for you
- Top ReactJS Best Practices for Frontend Teams
Delve into these comprehensive resources to enhance your understanding of ReactJS and VueJS. If you’re interested in a collaboration involving frontend development with ReactJS or VueJS, please feel free to reach out to our sales team to discuss potential projects. For those looking to join our dynamic and skilled team of frontend developers, we encourage you to contact our recruitment department. We are always eager to welcome new talents who are passionate about pushing the boundaries of frontend technology. Let’s explore the possibilities of working together!