scope.row 用法
时间: 2024-05-13 21:19:50 浏览: 20
`scope.row` 是在 Vue.js 的组件中使用的一个特殊属性,它表示当前行的数据对象。它常用于表格组件中的 `slot` 插槽中,以便在表格中显示每行的数据。
例如,在一个简单的表格组件中,可以使用 `scope.row` 来渲染每行的数据:
```html
<template>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr v-for="item in data" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.email }}</td>
</tr>
</tbody>
</table>
</template>
```
在上面的代码中,我们使用 `v-for` 指令渲染了一个表格,并在每一行中使用 `item` 来表示当前行的数据对象。这个 `item` 对象就是从父组件传递给子组件的数据数组中的一个元素。
如果我们想在表格中添加一个操作按钮,可以使用 `slot` 插槽,并通过 `scope.row` 属性来访问当前行的数据对象:
```html
<template>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr v-for="item in data" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>{{ item.email }}</td>
<td>
<slot name="action" :row="item">
<button @click="handleClick(item)">Edit</button>
</slot>
</td>
</tr>
</tbody>
</table>
</template>
```
在上面的代码中,我们在表格中添加了一个名为 `action` 的插槽,并在插槽中渲染了一个按钮。在插槽中,我们使用 `:row="item"` 将当前行的数据对象传递给插槽,以便在点击按钮时能够访问当前行的数据。
需要注意的是,在使用 `scope.row` 时,我们需要在组件中声明一个 `props`,以便将父组件传递过来的数据对象绑定到 `scope.row` 上。例如,在上面的代码中,我们可以在组件中声明一个 `props`:
```javascript
props: {
row: {
type: Object,
required: true
}
}
```
这样,我们就可以在组件的插槽中使用 `scope.row` 来访问当前行的数据对象了。