Vue.js tutorials with CRUD operations

 In this tutorial, we'll walk through creating a simple CRUD (Create, Read, Update, Delete) application using Vue.js. We'll manage the data in the frontend (without a backend or database) and use localStorage to persist data even after the page is refreshed. Vue.js is a progressive JavaScript framework that is easy to integrate into projects.

Steps:

  1. Set up the Vue.js Project
  2. Create the components for CRUD operations
  3. Use localStorage for data persistence
  4. Test the application

1. Set Up the Vue.js Project

First, let's create a basic Vue.js app. If you don't have Vue CLI installed, you can install it using npm:

bash
npm install -g @vue/cli

Now, create a new Vue project:

bash
vue create vue-crud-app

Navigate into your project directory:

bash
cd vue-crud-app

To serve the application, run:

bash
npm run serve

This will start a local development server at http://localhost:8080/.


2. Create the Components for CRUD Operations

We will create a Todo App where users can:

  • Create new todos
  • Read (view) the list of todos
  • Update an existing todo
  • Delete a todo

2.1. Modify the App.vue

First, we'll edit the App.vue file to include the necessary components and functionality.

vue
<template> <div id="app"> <h1>Vue.js CRUD App</h1> <!-- Form for adding and editing todos --> <form @submit.prevent="handleSubmit"> <input v-model="newTodo" type="text" placeholder="Add a new todo" required /> <button type="submit">{{ isEditMode ? 'Update Todo' : 'Add Todo' }}</button> </form> <!-- Todo List --> <ul> <li v-for="(todo, index) in todos" :key="index"> <span :class="{ completed: todo.completed }">{{ todo.text }}</span> <button @click="editTodo(index)">Edit</button> <button @click="deleteTodo(index)">Delete</button> <button @click="toggleCompletion(index)"> {{ todo.completed ? 'Undo' : 'Complete' }} </button> </li> </ul> </div> </template> <script> export default { data() { return { newTodo: '', isEditMode: false, editIndex: null, todos: JSON.parse(localStorage.getItem('todos')) || [] }; }, methods: { handleSubmit() { if (this.isEditMode) { this.updateTodo(); } else { this.addTodo(); } }, addTodo() { if (this.newTodo.trim() === '') return; this.todos.push({ text: this.newTodo, completed: false }); this.saveTodos(); this.newTodo = ''; // Reset the input field }, editTodo(index) { this.newTodo = this.todos[index].text; this.isEditMode = true; this.editIndex = index; }, updateTodo() { if (this.newTodo.trim() === '') return; this.todos[this.editIndex].text = this.newTodo; this.saveTodos(); this.newTodo = ''; // Reset the input field this.isEditMode = false; // Reset to add mode this.editIndex = null; // Reset the index }, deleteTodo(index) { this.todos.splice(index, 1); this.saveTodos(); }, toggleCompletion(index) { this.todos[index].completed = !this.todos[index].completed; this.saveTodos(); }, saveTodos() { localStorage.setItem('todos', JSON.stringify(this.todos)); } } }; </script> <style> /* Add some basic styling */ #app { max-width: 600px; margin: 0 auto; text-align: center; } input { padding: 10px; width: 60%; } button { padding: 10px; margin: 5px; cursor: pointer; } .completed { text-decoration: line-through; } ul { list-style: none; padding: 0; } li { display: flex; justify-content: space-between; margin: 10px 0; } li button { padding: 5px; cursor: pointer; } form { margin-bottom: 20px; } </style>

Explanation:

  1. HTML Form:

    • The form allows the user to input a new todo. The v-model directive binds the input field to the newTodo data property.
    • The form also conditionally renders the button text depending on whether it's in "edit" mode or "add" mode.
  2. Todos List:

    • We loop through the todos array and display each todo item in an unordered list.
    • Each todo has buttons for editing, deleting, and toggling its completion status.
  3. Methods:

    • addTodo: Adds a new todo to the list and stores it in localStorage.
    • editTodo: Sets the input field with the todo's text and switches to edit mode.
    • updateTodo: Updates an existing todo and switches back to add mode.
    • deleteTodo: Deletes the selected todo.
    • toggleCompletion: Marks a todo as completed or incomplete.
    • saveTodos: Saves the todos array to localStorage for persistence across page refreshes.
  4. Styling:

    • Simple CSS for basic styling. The .completed class is used to apply a line-through effect on completed todos.

3. Use localStorage for Data Persistence

By using localStorage, the todos will persist even when the user refreshes the page or closes and reopens the browser. The todos are stored as a JSON string in localStorage.

In the data property of our Vue component, we initialize the todos array by retrieving the stored value from localStorage. If there is no saved todos, we default to an empty array.

4. Testing the Application

To test the application:

  1. Run your Vue app using the following command:

    bash
    npm run serve
  2. Open the app in your browser at http://localhost:8080/.

  3. You should see:

    • A form to enter new todos.
    • A list of todos with options to edit, delete, and mark as completed.
  4. Test the CRUD functionality:

    • Create: Add a new todo and see it added to the list.
    • Read: View the list of todos.
    • Update: Click the "Edit" button, change the text, and update it.
    • Delete: Click the "Delete" button to remove a todo.
    • Toggle Completion: Click the "Complete" button to mark the todo as completed.

Conclusion

In this tutorial, we built a simple Vue.js CRUD app where you can:

  • Create new todos.
  • Read (view) the list of todos.
  • Update a todo.
  • Delete a todo.
  • Use localStorage to persist the data.

This app demonstrates the power of Vue.js and how you can easily manage state and user interactions with simple components and methods. You can extend this app by adding more advanced features, like input validation, due dates, or even a backend API.

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

oAuth in angular