screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <table> <h3>Vue Js push to array with key</h3> <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tbody> <tr v-for="(item, index) in items" :key="item.id"> <td>{{ item.id }}</td> <td>{{ item.name }}</td> </tr> </tbody> </table> <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> <script> new Vue({ el: '#app', data() { return { items: [ { id: 1, name: "Item 1" }, { id: 2, name: "Item 2" }, { id: 3, name: "Item 3" }, ], newItemName: "", }; }, methods: { addItem() { // Create a new item object with a unique ID const newItem = { id: Date.now(), name: this.newItemName, }; // Push the new item object into the items array this.items.push(newItem); // Clear the input field this.newItemName = ""; }, }, }); </script> <style scoped> table { border-collapse: collapse; width: 100%; max-width: 600px; margin: 0 auto; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } tr:nth-child(even) { background-color: #f2f2f2; } tr:hover { background-color: #ddd; } form { display: flex; align-items: center; margin-top: 16px; } label { margin-right: 8px; } input[type="text"] { flex: 1; border: 1px solid #ddd; padding: 8px; font-size: 16px; line-height: 1.5; border-radius: 4px; } button[type="submit"] { background-color: #4CAF50; color: #fff; border: none; padding: 12px 16px; font-size: 16px; border-radius: 4px; cursor: pointer; margin-left: 8px; } button[type="submit"]:hover { background-color: #3e8e41; } </style> </body> </html>