看一个例子:
<html> head> script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </bodydiv id="app"> ul> li v-for="(item,index) in arr"> 索引:{{index}},值:{{item}} li="item in arr2" {{item.color}} input type="button" @click="add" value="添加颜色"="remove"="移除颜色"div var app = new Vue({ el: '#app',data: { arr: ['mike','bob','tom','jack'],arr2: [{ color: 'red' },{ color: 'blue' },{ color: 'yellow' }],},methods: { add: function () {
//添加一个元素 this.arr2.push({ color: 'black' }); },remove: function () {
//移除左边第一个元素 this.arr2.shift(); },}) >
效果:
点击添加颜色会在末尾添加一个black,点击删除颜色会删除掉第一个颜色:
说明:
v-for用于根据数据生成列表结构。
数组常和v-for使用。
语法是(item,index) in 数据。item是具体值,index是索引。
item和index可以结合其他指令一起使用。