screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> </head> <body> <h2>Vue js Table Sort by Date </h2> <div id="app"> <table> <thead> <tr> <th> <button @click="sortTable">{{ sortBy }} {{ sortOrder === 'asc' ? '▲' : '▼' }}</button> </th> </tr> </thead> <tbody> <tr v-for="(item, index) in tableData" :key="index"> <td>{{ item.date }}</td> <td>{{ item.name }}</td> </tr> </tbody> </table> </div> <script type="module"> const app = Vue.createApp({ data() { return { sortOrder: 'asc', sortBy: 'date', tableData: [ { name: 'Andrew', date: '2022-02-10' }, { name: 'David', date: '2022-03-01' }, { name: 'John', date: '2022-01-15' }, { name: 'Joe', date: '2023-01-15' } ] } }, mounted() { this.sortTable() }, methods: { sortTable() { this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc' this.tableData.sort((a, b) => { const sortOrder = this.sortOrder === 'asc' ? 1 : -1 const aValue = a[this.sortBy] const bValue = b[this.sortBy] if (aValue > bValue) { return sortOrder } else if (aValue < bValue) { return -sortOrder } else { return 0 } }) } } }); app.mount("#app"); </script> </script> <style scoped> table { border-collapse: collapse; width: 100%; max-width: 800px; margin: 0 auto; } thead { background-color: #eee; } th, td { padding: 8px; text-align: left; } th { font-weight: bold; } tbody tr:nth-child(even) { background-color: #f2f2f2; } button { background-color: #4CAF50; border: none; color: white; padding: 8px 16px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } button:focus { outline: none; } button:hover { background-color: #3e8e41; } button:active { background-color: #3e8e41; transform: translateY(2px); } </style> </body> </html>