1. 程式人生 > >理解 Vue.js中的v-for功能

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

我們如果用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);