elementui scope
ElementUI Scope 的使用方法
ElementUI 中的 scope 通常用于表格组件(el-table)的自定义列模板中,用于访问当前行的数据。以下是具体的使用场景和方法。
自定义列模板中使用 scope
在 el-table-column 中,可以通过 scoped slot 访问当前行的数据。scope 是一个对象,包含 row(当前行数据)、column(当前列信息)、$index(行索引)等属性。

<el-table :data="tableData">
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column label="操作">
<template #default="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.row 是当前行的数据对象,可以直接用于操作或显示。例如,在按钮点击事件中传递当前行的数据:

methods: {
handleEdit(row) {
console.log('编辑行数据:', row);
},
handleDelete(index) {
console.log('删除行索引:', index);
}
}
动态生成列内容
通过 scope 可以动态生成列内容,例如根据行数据渲染不同的按钮或样式:
<el-table-column label="状态">
<template #default="scope">
<el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
{{ scope.row.status }}
</el-tag>
</template>
</el-table-column>
结合 v-if 条件渲染
可以根据 scope 中的数据条件渲染部分内容:
<el-table-column label="操作">
<template #default="scope">
<el-button v-if="scope.row.status !== 'disabled'">启用</el-button>
</template>
</el-table-column>
注意事项
scope是插槽作用域的对象,必须在template中使用#default或v-slot:default接收。- 如果需要访问多级数据,可以通过
scope.row.property的方式获取嵌套属性。 - 在 Vue 3 中,
scoped slot的语法与 Vue 2 略有不同,需使用#default或v-slot:default。






