iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 16
0
Modern Web

Vue.JS且戰且飛系列 第 18

Vue.JS且戰且飛(十八)

自寫小工具list order by

jsfiddle


<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>

上一篇
Vue.JS且戰且飛(十七)
下一篇
Vue.JS且戰且飛(十九)
系列文
Vue.JS且戰且飛30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

2
paza
iT邦新手 5 級 ‧ 2016-12-21 23:51:09

可以簡化

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
                }
            }

/images/emoticon/emoticon33.gif

/images/emoticon/emoticon41.gif

我要留言

立即登入留言