v-for 指令:解决模板循环问题

时间:2023-01-29 23:54:43

v-for指令是循环渲染一组data中的数组,v-for 指令需要以 item in items 形式的特殊语法,items 是源数据数组并且item是数组元素迭代的别名。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>v-for 实例</title>
    <script type="text/javascript" src="../assets/js/vue.js"></script>
</head>
<body>
<h1>v-for 实例</h1>
<hr>
<div id="app">
   <ul>
       <li v-for="item in sortItems">
           {{item}}
       </li>
   </ul>
    <hr>
    <ul>
        <li v-for="(student,index) in sortStudents">
            {{index+1}}:{{student.name}}-{{student.age}}
        </li>
    </ul>
</div>
<script type="text/javascript">
    var app = new Vue({
        el:'#app',
        data:{
            items:[53,23,7,14,54,36,28],
            students:[
                {name:'Xurui',age:22},
                {name:'Xu',age:1},
                {name:'rui',age:18},
                {name:'yaya',age:6},
            ]
        },
        computed:{
            sortItems:function(){
                return this.items.sort(sortNumber);
            },
            sortStudents:function () {
                return sortByKey(this.students,'age');
            }
        }
    });
    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>