<!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"> <script type="text/javascript" src="http://cdn.suoluomei.com/common/js2.0/vue/v2.5.16/vue.js"></script> <title>v-for</title> </head> <body> <h1>v-for</h1> <hr> <div id="app"> <ul> <li v-for="item in tidis">{{ item }}</li> </ul> <hr> <ul> <!-- index是索引值 --> <li v-for="(student,index) in sortStudent"> {{index+1}}:{{student.name}} - {{student.age}} </li> </ul> </div> <script type="text/javascript"> var app = new Vue({ el: '#app', data: { items: [66, 90, 146, 189, 124, 78, 44, 119], students: [{ name: 'limeng', age: 25 }, { name: 'lili', age: 23 }, { name: 'yuyue', age: 20 }, { name: 'linlin', age: 33 } ] }, // computed计算属性,是在渲染数据之前进行的操作,在这里我们进行排序 computed: { // 在computed里新声明一个对象,如果不重新声明会污染原来的数据源,这是vue不允许的,所以需要重新声明一个对象,但是在上面循环的时候,要改变循环的对象 tidis: function () { // 在sort函数中传入自己的自己编写的数据排序的函数 return this.items.sort(sortNumber); }, sortStudent: function () { return sortByKey(this.students, 'age');//将studet数组中的数据按照年龄进行排序 } } }); //不要写在methods里面 // 普通数据的排序方法 function sortNumber(a, b) { return a - b } //数组对象方法排序: function sortByKey(array, key) { return array.sort(function (a, b) { var x = a[key]; var y = b[key]; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }); } </script> </body> </html>
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句