在 Vue3 中,你可以使用组件复用的方式来实现将一个表格的样式传到另一个表格上。

首先,你需要将第一个表格的样式封装成一个组件,例如:

<template>
  <table class='my-table'>
    <thead>
      <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
      </tr>
      <tr>
        <td>Data 4</td>
        <td>Data 5</td>
        <td>Data 6</td>
      </tr>
    </tbody>
  </table>
</template>

<script>
export default {
  name: 'MyTable',
}
</script>

<style scoped>
.my-table {
  border: 1px solid black;
  border-collapse: collapse;
}

.my-table th, .my-table td {
  border: 1px solid black;
  padding: 5px;
}
</style>

然后,在第二个表格中引用这个组件,并使用<slot>来接收第二个表格的数据:

<template>
  <table class='my-table'>
    <thead>
      <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
      </tr>
    </thead>
    <tbody>
      <slot></slot>
    </tbody>
  </table>
</template>

<script>
export default {
  name: 'MyTable2',
}
</script>

<style scoped>
.my-table {
  border: 1px solid black;
  border-collapse: collapse;
}

.my-table th, .my-table td {
  border: 1px solid black;
  padding: 5px;
}
</style>

最后,在父组件中使用第二个表格,并将要显示的数据通过<template>的方式传递给<slot>

<template>
  <div>
    <my-table2>
      <tr>
        <td>Data 1</td>
        <td>Data 2</td>
        <td>Data 3</td>
      </tr>
      <tr>
        <td>Data 4</td>
        <td>Data 5</td>
        <td>Data 6</td>
      </tr>
    </my-table2>
  </div>
</template>

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

export default {
  components: {
    MyTable2,
  },
}
</script>

通过这种方式,你就可以将一个表格的样式传递给另一个表格,并且在第二个表格中使用传递进来的数据来渲染表格内容。

Vue3 表格样式复用:将一个表格样式应用到另一个表格

原文地址: http://www.cveoy.top/t/topic/ohck 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录