牛叔叔 的笔记

好好学习

2021-03-10 17:44

使用ElementUI实现el-table列表选中行同步标签el-tag显示

牛叔叔

WEB前端

(4200)

(0)

收藏

在使用ElementUI开发时,可能需要实现el-table的选中和el-tag同步。

类似如下效果:

微信图片_20210310173222.png

希望表格选择改变,或者tag删除时,table和tag能同步选择情况。


查了一下官方文档,找到了一种解决方案如下。


首先el-table需要务必设置row-key,这个row-key作用:

row-key行数据的 Key,用来优化 Table 的渲染;在使用 reserve-selection 功能与显示树形数据时,该属性是必填的。类型为 String 时,支持多层访问:user.info.id,但不支持 user.info[0].id,此种情况请使用 FunctionFunction(row)/String

参考:https://element.eleme.cn/?#/zh-CN/component/table


这样当选表格中行复选框后,当重新搜索新数据时,选中过的数据依然会保留状态,再次搜索出现时会默认选中。(根据这个row-key来渲染的)


另外我们需要知道 table的选择改变,就可以将选择变化同步到tag的数据,这个事件选择selection-change即可。tag 的删除(close事件)也需要做一下数据同步处理(同步table的选中数据)。


上代码:

table和tag:

        <template v-for="(userinfo,index) in selectUserinfos">
            <el-popover placement="top-start" :title="userinfo.name" width="200" trigger="click"
              :content="userinfo.nickName" :key="index">
              <el-tag closable effect="dark" style="margin:5px;" slot="reference" @close="deleteSelection(userinfo,index)">
                {{userinfo.name}}
              </el-tag>
            </el-popover>
        </template>
        <el-table :data="userinfos" height="300" border   @selection-change="select" ref="table" :row-key="getRowKey">
            <el-table-column
            type="selection" :reserve-selection="true"
            width="55">
            </el-table-column>
            <el-table-column property="name" label="用户"></el-table-column>
            <el-table-column property="nickName" label="昵称" ></el-table-column>
        </el-table>


js部分

<script>
export default {
    data() {
      return {
          userinfos:[],
          selectUserinfos:[],
          getRowKey(row){
            return row.id;
          }
      };
    },
    created:function(){
        this.loaddatas();
    },
    methods: {
        select(selection){
            //表格的选择数据变化时,同步到tag数据
            this.selectUserinfos = selection;
        },
        loaddatas(){
            /*
            加载http://www.wanmait.com数据,省略。。。
            */
        },
        deleteSelection(userinfo,index){
            //el-tag的close事件,同步删除表格的选中数据
            this.selectUserinfos.splice(index,1);  
            this.$refs.table.selection.splice(index,1);
        }
        
    }
}
</script>



0条评论

点击登录参与评论