在Vue js中按名称自动排序API列表



你好,我是Vue,js领域的新手,我遇到了一个问题。我有一个API列表,其中包含不同的数据点,我正在尝试按first_name排序并加载到页面上:

<template>
<div> 

<div class="content-card">
<h1 class="title">List of users</h1>

<div v-for="peopleData in peopleDataList.data"  :key ="peopleData.id" class="people-data">
<div @load="sort('first_name')" v-bind:class="[sortBy === 'first_name' ? sortDirection : '']">


<div class="user-icon">
<img :src="peopleData.avatar" alt="Connection lost please reload">
</div>

<div class="user-info">
<div class="user-full_name"> 
{{peopleData.first_name}}
{{peopleData.last_name}}
</div>
<div class="user-email">
<!-- {{peopleData.email}} -->
</div>
</div>


<!-- make a mdel to display as menu with the data  -->
</div>
</div>
</div>
</div>
</template>
<script>

export default {
name: "List",

data() {
return {
peopleDataList: [],
sortBy: 'name',
sortDirection: 'asc',
};
}, 

// automatically call the data 
created() {
this.getpeopleData();
},

methods: {
getpeopleData() {
fetch("https://reqres.in/api/users?page=2")
.then(response => response.json())
.then(data => (this.peopleDataList = data));
},

sort: function(s){
if(s === this.sortBy) {
this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
}
this.sortBy = s;
}
},
watch: {
sortedProducts: function(){
return this.products.sort((p1,p2) => {
let modifier = 1;
if(this.sortDirection === 'desc') modifier = -1;
if(p1[this.sortBy] < p2[this.sortBy]) return -1 * modifier; if(p1[this.sortBy] > p2[this.sortBy]) return 1 * modifier;
return 0;
});
}
},

};
</script>

我已经看到多个指南使用@click来解决这个问题,但我想让它在加载时自动排序。我对Vue.js还是个新手,所以请别对我太苛刻。

不需要

<template>
<div class="initial-data-sort">
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
</tr>
</thead>
<tbody>
<tr v-for="user in users" :key="user.id">
<td>{{ user.id }}</td>
<td>{{ user.name }}</td>
<td>{{ user.email }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
users: [],
usersSorted: []
}
},
methods: {
getUsers() {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
this.users = response.data;
// Sort users
this.users.sort(this.compareNames);
})
.catch(error => console.log(error));
},
compareNames(a, b) {
const nameA = a.name.toLowerCase();
const nameB = b.name.toLowerCase();
let comparison = 0;
if (nameA > nameB) {
comparison = 1;
} else if (nameA < nameB) {
comparison = -1;
}
return comparison;
}
},
created() {
this.getUsers();
}
}
</script>

我有时保留数据数组的排序版本,因此包含'usersSorted',但在您的情况下可能不是必需的。

最新更新