理解 Vue.js中的v-for功能

来源:互联网 发布:二分查找算法举例说明 编辑:程序博客网 时间:2024/06/05 13:30

我们如果用html去写一个表格是很麻烦的一件事情,需要写很多的tr, th, td, 但是如果我们用了vue.js以后一切就变得如此简单。

下面是pug形式的html:

 table#example2(border='1' cellspacing='0')            tr                th(v-for='head in heads' :style='{width:tWidth, backgroundColor:thColor}') {{head}}            tr(v-for='item in items')                td(v-for='cell in item' :style='{width:tWidth, textAlign:tAlign}') {{cell}}

个人喜欢用pug,因为这会让html看起来更简洁,规整。其实pug也有一些指令操作,实现表格也比较简单,但是由于用了vue,所以就直接抛弃pug的js指令操作了,而只是用它的基础语法来写DOM。

接下来看下Vue的js代码:

new Vue({    el:'#example2',    data:{        items:[            {name:'张三',class:'One', sex:'男',score:'90'},            {name:'李四',class:'Two', sex:'男',score:'80'},            {name:'王五',class:'Three', sex:'女',score:'100'},            {name:'马六',class:'Four', sex:'男',score:'78'},            {name:'赵七',class:'Five', sex:'女',score:'88'}        ],        tWidth:'100px',        tAlign:'center',        thColor:'orange',        tBorder:'2px solid black'    },    computed:{        heads:function(){            return Object.keys(this.items[0]);         }    }})

看下运行结果:

这里写图片描述

这里用了3个v-for循环遍历了items。

  • 表头:得到第一组数据的所有对象属性,然后显示出来就是表头,这里用到了计算属性。
  • 表行:遍历items的每条数据,
  • 表单元格:遍历items的每条数据的每个对象,显示出表的内容。

是不是很简单?

当然,你需要用express来把pug渲染成html,下面是服务器代码: app.js

var express = require('express');var path = require('path');var app = express();app.engine('pug', require('pug').renderFile);app.set('views', __dirname + '/views');app.set('view engine', 'pug');app.use(express.static(path.join(__dirname, 'public')));app.get('/', function (req, res) {    res.render('pugVue', {title:'icon'});});app.listen(3000);