vue點擊按鈕給商品按照價格進行倒敘

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>按照商品價格倒敘</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <button @click="sortBtn()">點擊倒敘</button>
        <ul>
            <li v-for="(list, index) in goodList" :key="index">{{list.name}} ------------ {{list.gdPrice}}</li>
        </ul>
    </div>
    <script>
        var app = new Vue({
            el: '#app',
            data() {
                return {
                    goodList: [
                        {
                            name: '測試商品1',
                            gdPrice: 600
                        },
                        {
                            name: '測試商品2',
                            gdPrice: 700
                        },
                        {
                            name: '測試商品3',
                            gdPrice: 800
                        }
                    ]
                }
            },
            methods: {
                sortBtn () {
                    console.log('sort')
                    this.goodList.sort(this.sortMethods('gdPrice'))
                },
                sortMethods (property) {
                    return function(a,b){
                        var value1 = a[property]
                        var value2 = b[property]
                        return value2 - value1
                    }
                }
            },
        })
    </script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章