此例子中用
v-for
来遍历数组,
computed
的作用是,在数组进行渲染前改变传值,最终显示为
1,2,3,4,5,6,7
。如果想使用方法给数组排序,则必须给
computed
中
items
起别名,并且名称要和
v-for
属性中循环的绑定的名称保持一致。
<!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>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>
</div>
<script type="text/javascript">
var app = new Vue({
el:'#app',
data:{
items:[53,23,76,14,54,36,28]
},
computed:{
sortItems:function(){
return this.items.sort();
}
}
})
</script>
</body>
</html>