官方文档地址
列表渲染 https://cn.vuejs.org/v2/guide/list.html
简述
通过练习文档中例子,掌握以下知识点:
- v-for 的基础用法
- v-for 遍历对象的方法
- v-for 遍历对象 (A,B,C)分别代表 A-属性值 B-属性名 C-索引值
- 数组更新的七个方法,这些方法可以原地更新数组的值
- push()
- pop()
- shift()
- unshift()
- splice()
- sort()
- reverse()
- 替换数组的方法,这些方法不能原地更新数组值
- 对数组应用计算属性
练习代码
<template>
<div class="about">
<h1>v-for列表渲染</h1>
<hr />
<h3>基础用法</h3>
<ul id="example-1">
<li v-for="item in items" :key="item.message">{{item.message}}</li>
</ul>
<h3>带index索引</h3>
<ul id="example-1">
<li v-for="(item,index) in items" :key="item.message">{{index}} - {{item.message}}</li>
</ul>
<hr />
<h3>遍历对象</h3>
<ul id="v-for-object" class="demo">
<li v-for="value in object" :key="value">{{value}}</li>
</ul>
<h3>带属性名</h3>
<ul id="v-for-object" class="demo">
<li v-for="(value,title) in object" :key="value">{{title}} : {{value}}</li>
</ul>
<h3>带index</h3>
<ul id="v-for-object" class="demo">
<li v-for="(value,title,index) in object" :key="value">{{index}} {{title}} : {{value}}</li>
</ul>
<hr />
<h3>数组更新</h3>
<button @click="arrPush">push</button>
<button @click="arrPop">pop</button>
<button @click="arrShift">shift</button>
<button @click="arrUnshift">unshift</button>
<button @click="arrSplice">splice</button>
<button @click="arrSort">sort</button>
<button @click="arrReverse">reverse</button>
<button @click="arrFilter">保留偶数</button>
<ul>
<li v-for="(num,index) in numbers" :key="index">{{num}}</li>
</ul>
<hr />
<h3>计算属性</h3>
<ul>
<li v-for="(num,index) in evenNumbers" :key="index">{{num}}</li>
</ul>
<hr />
<h3>for循环中使用方法</h3>
<ul v-for="(set,index) in sets" :key="index">
<li v-for="n in even(set)" :key="n">{{ n }}</li>
</ul>
<hr />
<h3>v-for使用值范围</h3>
<div>
<span v-for="n in 10" :key="n">{{n}}</span>
</div>
<hr />
<h3>template使用v-for渲染一段元素:测试证明这样写不行,key只能写在ul上</h3>
<ul v-for="item in items" :key="item.message">
<template>
<li>{{ item.message }}</li>
<li class="divider" role="presentation"></li>
</template>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
items: [{ message: "Foo" }, { message: "Bar" }],
object: {
title: "How to do lists in Vue",
author: "Jane Doe",
publishedAt: "2016-04-10"
},
numbers: [1, 5, 2, 3],
sets: [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10]
]
};
},
methods: {
arrPush() {
this.numbers.push(4);
},
arrPop() {
this.numbers.pop();
},
arrShift() {
this.numbers.shift();
},
arrUnshift() {
this.numbers.unshift(9);
},
arrSplice() {
//替换可用这个方法
this.numbers.splice(0, 2, 10, 20);
},
arrSort() {
this.numbers.sort();
},
arrReverse() {
this.numbers.reverse();
},
arrFilter() {
this.numbers = this.numbers.filter(function(item) {
return item % 2 === 0;
});
},
even(nums) {
return nums.filter(function(num) {
return num % 2 === 0;
});
}
},
computed: {
evenNumbers: function() {
return this.numbers.filter(function(item) {
return item % 2 === 0;
});
}
}
};
</script>
网友评论