1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Vue: Basic CRUD</title> <style> table { border-collapse: collapse; } th, td { padding: 0 0.5rem; border: 1px solid black; } </style> </head> <body> <div id="app"> <button v-on:click="student={ username: '', email: '', id: '' }">New Student</button><br /> <input type="text" placeholder="username" v-model="student.username" /><br /> <input type="text" placeholder="email" v-model="student.email" /><br /> <button @click="saveStudent">{{student.id ? 'Update Student':'Create Student'}}</button><br /><br /> <input type="text" placeholder="Search..." v-model="filter"> <button @click="filter=''">x</button> <table> <thead> <tr> <th>#</th> <th>Id</th> <th>User</th> <th>Email</th> <th>Actions</th> </tr> </thead> <tbody> <tr v-for="(item, index) in filterStudent" :key="index"> <td>{{index + 1}}</td> <td>{{item.id}}</td> <td>{{item.username}}</td> <td>{{item.email}}</td> <td> <button @click="editStudent(item.id)">Edit</button> <button @click="deleteStudent(item.id)">Delete</button> </td> </tr> </tbody> </table> </div> <!-- <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> --> <script> const uuid = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1) const RootComponent = { data() { return { listStudent: [], student: { username: '', email: '', id: '' }, filter: "", } }, methods: { saveStudent() { if (!this.student.id) { this.student.id = uuid(); this.listStudent.push({ ...this.student }) } else { let find_student = this.listStudent.find(item => item.id == this.student.id); find_student.username = this.student.username; find_student.email = this.student.email; } this.student = { username: '', email: '', id: '' } }, editStudent(id) { let find_student = this.listStudent.find(item => item.id == id); this.student = { ...find_student }; }, deleteStudent(id) { this.listStudent = this.listStudent.filter(item => item.id !== id) } }, computed: { filterStudent() { return this.listStudent.filter(item => item.username.includes(this.filter)) } } } Vue.createApp(RootComponent).mount("#app") </script> </body> </html> |
CRUD – StudentList in one Component
Author: admin - Posted: 01/10/22 - Update: 03/11/22