使用iview2做一个表,效果如图:
先看看数据长什么样子:(如果photo为true,表示已经上传照片,照片那一列显示已上传,操作那一列显示两个按钮:重新上传、删除;否则照片那一列显示未上传,操作显示上传按钮)
Info:[
{name:"Lee",hobby:"篮球",photo:true},
{name:"Coco",hobby:"烹饪",photo:false},
{name:"Jimmy",hobby:"看书",photo:false},
{name:"Lora",hobby:"睡觉",photo:false},
{name:"John",hobby:"吃饭",photo:false},
],
1、【 render写法 】script的data中是这样写表头的,这也是第一种生成按钮的方法:
colunms:[
{title:"姓名",key:"name",minWidth:100, align: "center",},
{title:"爱好",key:"hobby",minWidth:100, align: "center",},
{title:"照片",key:"photo",minWidth:100, align: "center",render:(h,params)=>{
if (params.row.photo){
return h('div',[
h('span',"已上传"),
h('Icon',
{props:{type:'md-search',color:"#2d8cf0",size:"20"},
on:{click:()=>{this.showphoto(params.row)}}
}
)
])
}else {
return h('div',"未上传")
}
}},
{title:"操作",key:"action",minWidth:100, align: "center",slot:"action"}
],
此处,render函数写成箭头函数,第一个自动传入参数 h 为createElement函数,第二个自动传入参数 params 是一个对象,包含 row
、column
和 index
,分别指当前行数据,当前列数据,当前是第几行。这是iview规定的,详见:http://v4.iviewui.com/components/table#SX
render函数返回一个createElement函数用于创建Dom,createElement函数有3个参数:
- 标签名称(string):'div'、'span' 等
- 标签属性(可以是数组,也可以直接是一个装着属性的对象):[ h(...) , h(...) ],上面的代码,嵌套了createElement函数,即在div中再生成span标签和一个Icon,对应图上的 “ 已上传🔍 ” 。其中生成🔍设置了颜色、绑定了点击事件,是按照iview官网上写的。
- 标签内容(可以是数组或string)
此处也可以缺省第二个参数,直接 h('div',"未上传"),则直接生成一个“未上传”。
2、【 slot插槽- template写法 】template中的代码为:
<Table :columns="colunms" :data="Info">
<template slot-scope="{row,index}" slot="action" >
<Button type="warning" v-if="row.photo" @click="draw">重新上传</Button>
<Button type="error" v-if="row.photo" @click="deletephoto(row)">删除</Button>
<Button type="primary" v-if="!row.photo" @click="uploadphoto(row)">上传</Button>
</template>
</Table>
注意⚠️ 在data中的 colunms 里,已经声明 slot:
{title:"操作",key:"action",minWidth:100, align: "center",slot:"action"}
于是可以在Table里使用 slot="action" 的 template,配合使用slot-scope,slot-scope 的参数有 3 个:当前行数据 row,当前列数据 column,当前行序号 index。此处只使用2个参数。
参见iview官网文档:http://v4.iviewui.com/components/table#SX
还有,需要注意的是,我原本写的是,Table内有两个 template ,用 v-if 和 v-else 选择展示,发现不可以这样,只能有一个template ,显示逻辑 v-if 添加在 Button 内才可以正常显示我要的效果。
即不可以像下面这样写
<Table :columns="colunms" :data="Info">
<template slot-scope="{row,index}" slot="action" v-if="row.photo">
<Button type="warning" @click="draw">重新上传</Button>
<Button type="error" @click="deletephoto(row)">删除</Button>
</template>
<template slot-scope="{row,index}" slot="action" v-if="!row.photo">
<Button type="primary" @click="uploadphoto(row)">上传</Button>
</template>
</Table>
发现,有一部分的按钮没有渲染出来: