Creating a Simple CRUD Application with Vue.js

chintanonweb - Feb 15 - - Dev Community

Introduction

Vue.js is a popular JavaScript framework for building user interfaces. In this tutorial, we will walk through the process of creating a simple CRUD (Create, Read, Update, Delete) application using Vue.js. This tutorial assumes you have a basic understanding of HTML, CSS, and JavaScript.

Setting Up the Project

Before we begin, make sure you have Node.js and npm (Node Package Manager) installed on your machine. Open a terminal and run the following commands:

# Create a new Vue project
vue create vue-crud-app

# Navigate to the project folder
cd vue-crud-app

# Install Axios for making HTTP requests
npm install axios
Enter fullscreen mode Exit fullscreen mode

Creating the Vue Components

In Vue.js, the UI is divided into components. Let's create components for listing, adding, updating, and deleting items.

1. List.vue - Displaying Items

<template>
  <div>
    <h2>All Items</h2>
    <ul>
      <li v-for="item in items" :key="item.id">
        {{ item.name }}
        <button @click="editItem(item)">Edit</button>
        <button @click="deleteItem(item.id)">Delete</button>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [],
    };
  },
  methods: {
    editItem(item) {
      // Implement edit functionality
    },
    deleteItem(itemId) {
      // Implement delete functionality
    },
  },
  mounted() {
    // Fetch items from the server or an API
    // and assign them to the 'items' data property
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

2. Add.vue - Adding New Items

<template>
  <div>
    <h2>Add New Item</h2>
    <form @submit.prevent="addItem">
      <label for="itemName">Item Name:</label>
      <input type="text" id="itemName" v-model="newItemName" required />
      <button type="submit">Add Item</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newItemName: '',
    };
  },
  methods: {
    addItem() {
      // Implement add functionality
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

3. Edit.vue - Updating Items

<template>
  <div>
    <h2>Edit Item</h2>
    <form @submit.prevent="updateItem">
      <label for="editedItemName">Item Name:</label>
      <input type="text" id="editedItemName" v-model="editedItemName" required />
      <button type="submit">Update Item</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      editedItemName: '',
    };
  },
  methods: {
    updateItem() {
      // Implement update functionality
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

4. Delete.vue - Deleting Items

<template>
  <div>
    <h2>Delete Item</h2>
    <p>Are you sure you want to delete this item?</p>
    <button @click="confirmDelete">Yes</button>
    <button @click="cancelDelete">No</button>
  </div>
</template>

<script>
export default {
  methods: {
    confirmDelete() {
      // Implement delete functionality
    },
    cancelDelete() {
      // Navigate back to the list view or close the modal
    },
  },
};
</script>
Enter fullscreen mode Exit fullscreen mode

Implementing CRUD Operations

Now that we have our components, let's implement the CRUD operations in the main App.vue file.

<template>
  <div>
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App',
};
</script>

<style>
/* Add your styles here */
</style>
Enter fullscreen mode Exit fullscreen mode

Routing

We'll use Vue Router for navigation. Set up the router in the src/router/index.js file:

import Vue from 'vue';
import VueRouter from 'vue-router';
import List from '../components/List.vue';
import Add from '../components/Add.vue';
import Edit from '../components/Edit.vue';
import Delete from '../components/Delete.vue';

Vue.use(VueRouter);

const routes = [
  { path: '/', component: List },
  { path: '/add', component: Add },
  { path: '/edit/:id', component: Edit },
  { path: '/delete/:id', component: Delete },
];

const router = new VueRouter({
  routes,
});

export default router;
Enter fullscreen mode Exit fullscreen mode

Don't forget to import the router in main.js and add it to the Vue instance:

import Vue from 'vue';
import App from './App.vue';
import router from './router';

Vue.config.productionTip = false;

new Vue({
  render: (h) => h(App),
  router,
}).$mount('#app');
Enter fullscreen mode Exit fullscreen mode

Fetching and Displaying Data

In the List.vue component, use Axios to fetch data when the component is mounted:

// Inside the List.vue component
import axios from 'axios';

// ...

export default {
  // ...

  mounted() {
    axios.get('https://api.example.com/items').then((response) => {
      this.items = response.data;
    });
  },
};
Enter fullscreen mode Exit fullscreen mode

Adding Items

In the Add.vue component, implement the addItem method:

// Inside the Add.vue component
import axios from 'axios';

// ...

export default {
  // ...

  methods: {
    addItem() {
      axios.post('https://api.example.com/items', { name: this.newItemName }).then(() => {
        // Clear the input field after adding the item
        this.newItemName = '';
        // Optionally, navigate to the list view
        this.$router.push('/');
      });
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

Updating and Deleting Items

Similar to adding items, implement the update and delete functionality in the Edit.vue and Delete.vue components using the appropriate HTTP methods.

Conclusion

Congratulations! You've created a simple CRUD application with Vue.js. This tutorial covered the basics of setting up a Vue project, creating components, implementing routing, and performing CRUD operations. Feel free to enhance the application by adding features like validation, error handling, or user authentication. Vue.js provides a flexible and powerful framework for building modern web applications. Happy coding!

FAQs

Q: Can I use a different data storage backend?

Yes, you can use any backend of your choice, such as Firebase, Express.js with MongoDB, or Django with PostgreSQL. Adjust the HTTP requests in the CRUD operations accordingly.

Q: How can I add form validation to the Add and Edit components?

You can use libraries like Vuelidate or implement custom validation logic in your methods. Vue.js provides a flexible data-binding system that makes it easy to work with form inputs and validation.

Q: Is Vue.js suitable for large-scale applications?

Yes, Vue.js is suitable for large-scale applications. It provides tools and patterns for managing

state, component communication, and code organization. Additionally, Vue.js allows you to progressively adopt its features, making it easy to integrate into existing projects.

Q: How can I deploy my Vue.js CRUD application?

You can deploy your Vue.js application to platforms like Netlify, Vercel, or GitHub Pages. These platforms offer easy deployment options for front-end applications. Additionally, you can configure your own server or use serverless functions for the backend if needed.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .