<html>
<head>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<div class="table-container">
<h3>Vue Js Table Add Row </h3>
<button @click="showModal = true" class="add-button">Add Row</button>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in tableData" :key="index">
<td>{{ row.name }}</td>
<td>{{ row.age }}</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-container" v-if="showModal">
<div class="modal">
<h2>Add Row</h2>
<form @submit.prevent="addRow">
<label>
Name:
<input type="text" v-model="newRow.name" />
</label>
<label>
Age:
<input type="number" v-model.number="newRow.age" />
</label>
<button type="submit" class="add-button">Add</button>
<button @click="showModal = false" class="cancel-button">Cancel</button>
</form>
</div>
</div>
</div>
<script type="module">
const app = Vue.createApp({
// Define the data properties and methods for the app
data() {
return {
tableData: [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 },
],
newRow: { name: "", age: "" },
showModal: false,
};
},
methods: {
addRow() {
if (this.newRow.name && this.newRow.age) {
this.tableData.push({ ...this.newRow });
this.newRow.name = "";
this.newRow.age = "";
this.showModal = false;
}
},
},
});
app.mount("#app");
</script>
<style scoped>
/* CSS code */
.table-container {
max-width: 600px;
margin: 0 auto;
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 1em;
}
thead th {
background-color: #f5f5f5;
text-align: left;
padding: 0.5em 1em;
border-bottom: 1px solid #ddd;
}
tbody tr:nth-child(even) {
background-color: #f9f9f9;
}
td {
padding: 0.5em 1em;
border-bottom: 1px solid #ddd;
}
td:first-child {
font-weight: bold;
}
.modal-container {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal {
background-color: #fff;
padding: 1em;
border-radius: 0.5em;
}
.modal h2 {
margin-top: 0;
}
input[type="text"],
input[type='number'] {
padding: 0.5em 1em;
font-size: 1em;
border-radius: 0.25em;
border: 1px solid #ccc;
}
input[type="text"]:focus {
outline: none;
box-shadow: 0 0 0 2px #c8e6c9;
}
.add-button {
background-color: #4caf50;
color: #fff;
border: none;
padding: 0.5em 1em;
border-radius: 0.25em;
font-size: 1em;
cursor: pointer;
transition: background-color 0.3s;
}
.add-button:hover {
background-color: #3e8e41;
}
.add-button:focus {
outline: none;
box-shadow: 0 0 0 2px #c8e6c9;
}
.cancel-button {
background-color: #f44336;
color: #fff;
border: none;
padding: 0.5em 1em;
border-radius: 0.25em;
font-size: 1em;
cursor: pointer;
transition: background-color 0.3s;
}
.cancel-button:hover {
background-color: #e53935;
}
.cancel-button:focus {
outline: none;
box-shadow: 0 0 0 2px #ffcdd2;
}
</style>
</body>
</html>