In previous article we employed jQuery to create dynamic input fields in an old fashion way. Let’s move ahead and use Vue to create the same functionality with modern syntax.
Here we’ll use Tailwind along with Vue for managing look and feel. Remember this, incorporating Vue and Tailwind directly using <script> is not recommended – that’s just for quick prototyping; for production, use any bundling / compiling tool such as Vite (normally each stack comes along with a build tool…so no worries).
Let’s open an editor of your choice and then insert following code;
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue Dynamic Input Fields</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body>
<div id="app" class="bg-gray-100 rounded-lg shadow m-4">
<div class="grid grid-cols-8 text-gray-500">
<div class="col-span-2">
<label class="p-2 m-2">Item</label>
</div>
<div class="col-span-2">
<label class="p-2 m-2">Quantity</label>
</div>
<div class="col-span-2">
<label class="p-2 m-2">Rate</label>
</div>
</div>
<div class="grid grid-cols-8">
<template v-for='(row, index) in rows' :key="index">
<div class="col-span-2 m-1">
<input v-model="row.item" type="text" class="p-1 w-full rounded-md border border-gray-300"/>
</div>
<div class="col-span-2 m-1">
<input v-model="row.quantity" type="text" class="p-1 w-full rounded-md border border-gray-300"/>
</div>
<div class="col-span-2 m-1">
<input v-model="row.rate" type="text" class="p-1 w-full rounded-md border border-gray-300"/>
</div>
<div class="col-span-2 m-1">
<button v-if="index > 0" @click="deleteRow(index)" class="border bg-red-600 hover:bg-red-700 text-white rounded-md px-2 py-1 ml-2 inline-block" >X</button>
</div>
</template>
<div class="p-4">
<button class="bg-indigo-600 hover:bg-indigo-700 text-white text-center text-sm rounded-md px-4 py-1" @click="addRow" >Add Row</button>
</div>
</div>
</div>
<script>
const { createApp } = Vue
createApp({
data() {
return {
rows: [{
item:'', quantity:'', rate:''
}]
}
},
methods: {
addRow() {
this.rows.push({item:'', quantity:'', rate:''})
},
deleteRow(index){
this.rows.splice(index,1);
}
}
}).mount('#app')
</script>
</body>
</html>
Now save it as an HTML file and open it in the browser. Sweet! Same results with neat and clean syntax…
2 thoughts on “Dynamic input fields using Vue”