自寫小工具list order by
<html>
<head>
<meta charset="UTF-8">
<title>自寫小工具list order by</title>
</head>
<body>
<div id="show">
<input @click="orderBy" type="button" value="order by">
<ul>
<li v-for="item in list">{{ item }}</li>
</ul>
</div>
</body>
<script src="vue.js"></script>
<script>
// start app
new Vue({
el: '#show',
data: {
sort: true,
list: [8, 7, 6, 14, 23, 47, 98, 512, 554, 14, 52]
},
methods: {
orderBy: function () {
if (this.sort) {
this.list = this.list.sort(function(a, b) {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
this.sort = false
} else {
this.list = this.list.sort(function(a, b) {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
} else {
return 0;
}
});
this.sort = true
}
}
}
})
</script>
</html>
可以簡化
orderBy: function () {
if (this.sort) {
this.list = this.list.sort(function(a, b) {
return a-b;
});
this.sort = false
} else {
this.list = this.list.sort(function(a, b) {
return b-a;
});
this.sort = true
}
}