返回

让人耳目一新的标签封装方法:Vue+Element-UI表格的标签(插槽)应用实例

前端

在很多系统中,表格经常需要添加各种各样的标签来标记某些属性。在Element-UI中,添加标签非常简单,最重要的是利用了Vue的插槽slot特性。

什么是插槽?

插槽(slot)是一种用于在子组件中留占位符的特性,当父组件使用这个子组件时,可以将自己的内容填入这个占位符,从而实现子组件和父组件之间的数据传递和交互。

在Element-UI中,插槽的使用非常广泛,比如在表格中,就可以使用插槽来添加各种各样的标签,实现更复杂的功能。

如何在Vue+Element-UI中使用插槽封装表格?

1. 创建子组件

首先,我们需要创建一个子组件,并在其中留一个占位符。

<template>
  <el-table :data="tableData">
    <el-table-column prop="name">
      <template slot="header">
        姓名
      </template>
      <template slot="body">
        {{ row.name }}
      </template>
    </el-table-column>
    <el-table-column prop="age">
      <template slot="header">
        年龄
      </template>
      <template slot="body">
        {{ row.age }}
      </template>
    </el-table-column>
    <el-table-column>
      <template slot="header">
        操作
      </template>
      <template slot="body">
        <button @click="handleEdit(row)">编辑</button>
        <button @click="handleDelete(row)">删除</button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  data() {
    return {
      tableData: [
        {
          name: 'John Doe',
          age: 30
        },
        {
          name: 'Jane Doe',
          age: 25
        }
      ]
    }
  },
  methods: {
    handleEdit(row) {
      console.log('编辑', row)
    },
    handleDelete(row) {
      console.log('删除', row)
    }
  }
}
</script>

在这个子组件中,我们定义了两个插槽,一个是header插槽,另一个是body插槽。

2. 在父组件中使用子组件

接下来,我们需要在父组件中使用这个子组件。

<template>
  <div>
    <my-table></my-table>
  </div>
</template>

<script>
import MyTable from './MyTable.vue'

export default {
  components: {
    MyTable
  }
}
</script>

在父组件中,我们使用<my-table>标签来引用子组件。

3. 在子组件中填充插槽

最后,我们需要在子组件中填充插槽。

<template>
  <el-table :data="tableData">
    <el-table-column prop="name">
      <template slot="header">
        姓名
      </template>
      <template slot="body">
        {{ row.name }}
      </template>
    </el-table-column>
    <el-table-column prop="age">
      <template slot="header">
        年龄
      </template>
      <template slot="body">
        {{ row.age }}
      </template>
    </el-table-column>
    <el-table-column>
      <template slot="header">
        操作
      </template>
      <template slot="body">
        <button @click="handleEdit(row)">编辑</button>
        <button @click="handleDelete(row)">删除</button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import { ref } from 'vue'

export default {
  setup() {
    const tableData = ref([
      {
        name: 'John Doe',
        age: 30
      },
      {
        name: 'Jane Doe',
        age: 25
      }
    ])

    return {
      tableData
    }
  },
  methods: {
    handleEdit(row) {
      console.log('编辑', row)
    },
    handleDelete(row) {
      console.log('删除', row)
    }
  }
}
</script>

在子组件中,我们使用<template slot="header"><template slot="body">标签来填充插槽。

总结

通过使用插槽,我们可以很容易地在Vue+Element-UI中封装表格,实现更复杂的功能。