How to perform dynamic Form addition and deletion in Vue js ?
Dynamic element manipulation is the backbone of any dynamic web application of modern times.
Static codes or User Interface are not any more relevant. Dynamic manipulation
saves us time and resources, reduces code redundancy and looks pretty in the eyes.
To start with this concept below here is a very simple source code of dynamic form addition and subtraction
and the data manipulation of their respective form index using Vue js.
To start with this concept below here is a very simple source code of dynamic form addition and subtraction
and the data manipulation of their respective form index using Vue js.
I have used bootstrap for a very minimalist design and vue cdn for this example.
See this demo on JsFiddle.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Vue Js exapmles</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<h1> Dynamic Form Using Vue js </h1>
<section id="container">
<div class="form-wrapper" v-for="(list,index) in itr">
<!-- displaying text on top right -->
<div class="form-container">
<div class="display">
Title: {{formdata.title[index]}}
<hr >
Author: {{formdata.author[index]}}
</div>
<div class="button">
<button @click="addForm()" class="btn btn-primary">Add </button>
<button @click="delForm(index)" class="btn btn-danger">Delete </button>
</div>
Title : <br />
<input type="text" placeholder="Enter title"
v-model="formdata.title[index]" class="form">
</div>
<div class="form-container">
Author : <br />
<input type="text" placeholder="Enter Author name"
v-model="formdata.author[index]" class="form">
</div>
</div>
</section>
</html>
<script src="https://kit.fontawesome.com/991c42112a.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
var app = new Vue({
el: "#container",
data() {
return{
formdata: { title: [], author: [] },
itr: ['']
}
},
methods: {
addForm(){
// const count= ++this.itr
this.itr.push('');
console.log(this.formdata);
},
delForm(id){
this.itr.splice(id,1);
this.formdata.title.splice(id,1);
this.formdata.author.splice(id,1);
}
}
});
</script>
<style>
#container{
padding: 30px;
display: inline;
}
.form-wrapper{
border: 1px solid black;
padding: 5px;
border-radius: 5px;
position: relative;
width: 40%;
margin-bottom: 4px;
}
.form{
border: 1px solid green;
padding: 5px;
border-radius: 4px;
width: 40%;
}
.display{
width: 40%;
border-radius: 4px;
/* border: 1px solid green; */
padding: 10px;
position: absolute;
bottom: 3px;
right:3px;
}
.button{
position: absolute;
top: 2px;
right: 3px;
}
.form-container{
display: block;
}
</style>
Comments
Post a Comment