elementui scope
ElementUI 中 scope 的用法
在 ElementUI 中,scope 主要用于表格(el-table)和树形控件(el-tree)的自定义列或节点渲染,允许访问当前行的数据或节点的上下文信息。
el-table 中的 scope
在表格中,scope 通常用于自定义列模板(slot-scope 或 v-slot),获取当前行的数据、索引等信息。
<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column label="操作">
<template v-slot="scope">
<el-button @click="handleEdit(scope.row)">编辑</el-button>
<el-button @click="handleDelete(scope.$index)">删除</el-button>
</template>
</el-table-column>
</el-table>
scope.row:当前行的数据对象。scope.$index:当前行的索引(从 0 开始)。scope.column:当前列的信息(如property、label)。
el-tree 中的 scope
在树形控件中,scope 用于自定义节点内容,可以访问节点的数据和层级信息。
<el-tree :data="treeData">
<template v-slot="{ node, data }">
<span>{{ node.label }}</span>
<span v-if="data.isLeaf">(叶子节点)</span>
</template>
</el-tree>
node:当前节点的信息(如label、level)。data:当前节点的数据对象(即treeData中的某一项)。
使用作用域插槽(Scoped Slot)
在 Vue 2.x 中,slot-scope 语法如下:
<el-table :data="tableData">
<el-table-column label="操作">
<template slot-scope="scope">
<el-button @click="handleClick(scope.row)">操作</el-button>
</template>
</el-table-column>
</el-table>
在 Vue 3.x 中,推荐使用 v-slot 语法:
<el-table :data="tableData">
<el-table-column label="操作">
<template v-slot="scope">
<el-button @click="handleClick(scope.row)">操作</el-button>
</template>
</el-table-column>
</el-table>
注意事项
- 确保
scope变量名正确,如v-slot="{ row, index }"或v-slot="props"。 - 在 Vue 3 中,
slot-scope已被废弃,推荐使用v-slot。 - 如果只需要
row数据,可以解构赋值:v-slot="{ row }"。
通过合理使用 scope,可以灵活定制 ElementUI 表格和树形控件的渲染逻辑。







