vue里數組排序示例


vue的默認排序方式
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <template v-for="user in userInfo">
        <li>姓名:{{user}}</li>
      </template>
    </div>
    <script>
        var v=new Vue({
            el:"#app",
            data:{
                userInfo:['zhangsan','aisi','wangwu']
            }
        });
       v.userInfo.sort();
    </script>
  </body>
</html>
 
改寫排序方式的示例
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="app">
      <template v-for=" user in  userInfoSorted">
        <li>姓名:{{user.name}}</li>
      </template>
    </div>
    <script>
      var v = new Vue({
        el: "#app",
        data: {
          userInfo: [
            { name: "zhangsan" },
            { name: "aisi" },
            { name: "wangwu" },
          ],
        },
        computed: {
           userInfoSortedfunction () {
// a,b參數代表的是user 按照 長度降序排序
            return this.userInfo.sort(function (a, b) {
              return -(a.name.length - b.name.length);
            });
          },
        },
      });
    </script>
  </body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM