npm install -g @vue/cli
vue create vue-crud-app
cd vue-crud-app
npm install axios
For demonstration, we'll use https://jsonplaceholder.typicode.com/posts
as a fake API.
To manage API calls, create a new file:
📂 src/services/api.js
import axios from "axios";
const API_URL = "https://jsonplaceholder.typicode.com/posts";
export default {
getPosts() {
return axios.get(API_URL);
},
createPost(post) {
return axios.post(API_URL, post);
},
updatePost(id, post) {
return axios.put(`${API_URL}/${id}`, post);
},
deletePost(id) {
return axios.delete(`${API_URL}/${id}`);
}
};
📂 src/components/PostManager.vue
<template>
<div>
<h2>Vue CRUD Operations</h2>
<!-- Form to Add Post -->
<form @submit.prevent="addPost">
<input v-model="newPost.title" placeholder="Enter post title" required />
<textarea v-model="newPost.body" placeholder="Enter post content" required></textarea>
<button type="submit">Add Post</button>
</form>
<!-- Display Posts -->
<ul>
<li v-for="post in posts" :key="post.id">
<strong>{{ post.title }}</strong>
<p>{{ post.body }}</p>
<button @click="editPost(post)">Edit</button>
<button @click="deletePost(post.id)">Delete</button>
</li>
</ul>
</div>
</template>
<script>
import apiService from "../services/api";
import { ref, onMounted } from "vue";
export default {
setup() {
const posts = ref([]);
const newPost = ref({ title: "", body: "" });
// Fetch Posts (Read)
const fetchPosts = async () => {
try {
const response = await apiService.getPosts();
posts.value = response.data.slice(0, 5); // Limit to 5 posts
} catch (error) {
console.error("Error fetching posts:", error);
}
};
// Create Post
const addPost = async () => {
try {
const response = await apiService.createPost(newPost.value);
posts.value.unshift(response.data); // Add new post to list
newPost.value = { title: "", body: "" }; // Reset form
} catch (error) {
console.error("Error adding post:", error);
}
};
// Edit Post (Prefill form)
const editPost = (post) => {
newPost.value = { ...post };
};
// Update Post
const updatePost = async () => {
try {
await apiService.updatePost(newPost.value.id, newPost.value);
fetchPosts();
newPost.value = { title: "", body: "" }; // Reset form
} catch (error) {
console.error("Error updating post:", error);
}
};
// Delete Post
const deletePost = async (id) => {
try {
await apiService.deletePost(id);
posts.value = posts.value.filter((post) => post.id !== id);
} catch (error) {
console.error("Error deleting post:", error);
}
};
onMounted(fetchPosts);
return { posts, newPost, addPost, editPost, updatePost, deletePost };
}
};
</script>
Operation | Method | Function |
---|---|---|
Create | POST |
addPost() sends data to API |
Read | GET |
fetchPosts() retrieves data from API |
Update | PUT |
updatePost() modifies an existing post |
Delete | DELETE |
deletePost() removes a post |
By following these steps, you can integrate API-based CRUD functionality into your Vue.js applications. 🚀
@asadmukhtar