screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> </head> <body> <div id="app"> <h3>Vue Add Object to Specific Position in Array</h3> <form @submit.prevent="addNewObject"> <label> Name: <input type="text" v-model="newObject.name" /> </label> <label> Age: <input type="number" v-model="newObject.age" /> </label> <button>Add Object</button> </form> <table> <thead> <tr> <th>Name</th> <th>Age</th> <th>Actions</th> </tr> </thead> <tbody> <tr v-for="(object, index) in myArray" :key="object.name"> <td>{{ object.name }}</td> <td>{{ object.age }}</td> <td><button class="remove-btn" @click="removeObject(index)">Remove</button></td> </tr> </tbody> </table> </div> <script type="module"> const app = Vue.createApp({ data() { return { myArray: [ { name: "John", age: 30 }, { name: "Jane", age: 25 }, { name: "Bob", age: 40 } ], newObject: { name: "", age: "" } }; }, methods: { addNewObject() { this.myArray.splice(2, 0, this.newObject); this.newObject = { name: "", age: "" }; }, removeObject(index) { this.myArray.splice(index, 1); } } }) app.mount('#app') </script> <style scoped> #app { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; } h3 { font-size: 24px; margin-bottom: 20px; } form { display: flex; flex-direction: row; justify-content: space-between; align-items: center; margin-bottom: 20px; } label { display: flex; flex-direction: column; margin-right: 10px; } input[type="text"], input[type="number"] { padding: 10px; border-radius: 4px; border: 1px solid #ccc; margin-bottom: 10px; width: 100%; } label:first-child { margin-left: 0; } button { background-color: #008CBA; color: #fff; border: none; border-radius: 4px; padding: 10px 20px; cursor: pointer; transition: background-color 0.2s ease; margin-left: 10px; } button:hover { background-color: #006B8E; } table { width: 100%; border-collapse: collapse; } th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ccc; } th { background-color: #f2f2f2; font-weight: bold; } .remove-btn { background-color: #f44336; color: #fff; border: none; border-radius: 4px; padding: 6px 12px; cursor: pointer; transition: background-color 0.2s ease; } .remove-btn:hover { background-color: #d32f2f; } </style> </body> </html>