Vue排序数组后跟着索引(0,1,2,3,…)



我是vue的新手,我试图按名字对数组进行排序。我有一个按钮,应该按名字排序球员的名字。但是当我点击按钮时,它会抛出这样的错误。todos.player_name.sort()不是一个函数。下面是我在

上的代码JsFiddle =https://jsfiddle.net/ujjumaki/r6wp38yj/77/

<视图/strong>

<div id="app">
<table>
<tr>
<th><b>First Name  &nbsp;</b></th>
<th><b> Last Name &nbsp;</b> </th>
<th><b> ID </b> </th>
</tr>
<tr v-for="fetchName in todos.player_name">
<td>{{fetchName.first_name}}</td>
<td>{{fetchName.last_name}}</td>
<td>{{fetchName.id}}</td>
</tr>

</table>
<br>
<button v-on:click=alertName()>Sort by first name</button>
</div>

new Vue({
el: "#app",
data(){
return{
todos: {
mission:1,
player_name:[
{   
first_name: "Harry", last_name: "Kui" , id:'103',
},
{
first_name: "Ali", last_name: "Kui", id:'107',
},
{
first_name: "Bee", last_name: "Hui", id:'99',
}
]
}
}
},
methods: {
alertName: function(){
this.todos.player_name.sort(); /** sort function is throwing an error here **/
console.log(this.todos.player_name); /** and this does not format array objects followed by first name **/
}
}
})

这是因为仅通过调用Array.prototype.sort()而不使用任何比较器函数将默认为以下行为:

数组元素被转换为字符串,然后根据每个字符的Unicode码位值排序。

…这不是你想要的。相反,您将只希望使用String.prototype.localeCompare来比较first_name键返回的值,即:

this.todos.player_name.sort((a,b) => a.first_name.localeCompare(b.first_name));

参见下面的概念验证:

new Vue({
el: "#app",
data(){
return{
todos: {
mission:1,
player_name:[
{   
first_name: "Harry", last_name: "Kui" , id:'103',
},
{
first_name: "Ali", last_name: "Kui", id:'107',
},
{
first_name: "Bee", last_name: "Hui", id:'99',
}
]
}
}
},
methods: {
alertName: function(){
this.todos.player_name.sort((a,b) => a.first_name.localeCompare(b.first_name));
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<table>
<tr>
<th><b>First Name  &nbsp;</b></th>
<th><b> Last Name &nbsp;</b> </th>
<th><b> ID </b> </th>
</tr>
<tr v-for="fetchName in todos.player_name">
<td>{{fetchName.first_name}}</td>
<td>{{fetchName.last_name}}</td>
<td>{{fetchName.id}}</td>
</tr>

</table>
<br>
<button v-on:click=alertName()>Sort by first name</button>
</div>

最新更新