当前位置:首页 > VUE

用vue实现表格

2026-03-08 13:09:12VUE

使用 Vue 实现表格

Vue 提供了灵活的方式来实现动态表格,可以通过 v-for 指令结合数组数据渲染表格内容。以下是一个完整的实现示例。

基础表格实现

创建一个 Vue 组件,定义表格的数据结构和模板:

用vue实现表格

<template>
  <div>
    <table class="table">
      <thead>
        <tr>
          <th v-for="(header, index) in headers" :key="index">
            {{ header }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, rowIndex) in rows" :key="rowIndex">
          <td v-for="(cell, cellIndex) in row" :key="cellIndex">
            {{ cell }}
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      headers: ["ID", "Name", "Age", "Email"],
      rows: [
        [1, "John Doe", 25, "john@example.com"],
        [2, "Jane Smith", 30, "jane@example.com"],
        [3, "Bob Johnson", 22, "bob@example.com"],
      ],
    };
  },
};
</script>

<style>
.table {
  width: 100%;
  border-collapse: collapse;
}
.table th, .table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}
.table th {
  background-color: #f2f2f2;
}
</style>

动态数据绑定

如果需要从 API 获取数据,可以使用 axiosfetch 加载数据:

用vue实现表格

<template>
  <div>
    <table class="table">
      <!-- 表头同上 -->
      <tbody>
        <tr v-for="item in items" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.email }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [],
    };
  },
  async created() {
    try {
      const response = await fetch("https://api.example.com/users");
      this.items = await response.json();
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  },
};
</script>

添加排序功能

通过计算属性实现表格数据的排序:

<template>
  <div>
    <table class="table">
      <thead>
        <tr>
          <th @click="sortBy('id')">ID</th>
          <th @click="sortBy('name')">Name</th>
          <th @click="sortBy('age')">Age</th>
          <th @click="sortBy('email')">Email</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in sortedItems" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.email }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [
        { id: 1, name: "John Doe", age: 25, email: "john@example.com" },
        { id: 2, name: "Jane Smith", age: 30, email: "jane@example.com" },
        { id: 3, name: "Bob Johnson", age: 22, email: "bob@example.com" },
      ],
      sortKey: "",
      sortOrder: 1, // 1 for ascending, -1 for descending
    };
  },
  computed: {
    sortedItems() {
      if (!this.sortKey) return this.items;
      return [...this.items].sort((a, b) => {
        const valA = a[this.sortKey];
        const valB = b[this.sortKey];
        return this.sortOrder * (valA < valB ? -1 : valA > valB ? 1 : 0);
      });
    },
  },
  methods: {
    sortBy(key) {
      if (this.sortKey === key) {
        this.sortOrder *= -1;
      } else {
        this.sortKey = key;
        this.sortOrder = 1;
      }
    },
  },
};
</script>

添加分页功能

通过计算属性实现分页:

<template>
  <div>
    <table class="table">
      <!-- 表格内容同上 -->
    </table>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">Previous</button>
      <span>Page {{ currentPage }} of {{ totalPages }}</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">Next</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [], // 假设有大量数据
      currentPage: 1,
      itemsPerPage: 5,
    };
  },
  computed: {
    paginatedItems() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.items.slice(start, end);
    },
    totalPages() {
      return Math.ceil(this.items.length / this.itemsPerPage);
    },
  },
  methods: {
    nextPage() {
      if (this.currentPage < this.totalPages) this.currentPage++;
    },
    prevPage() {
      if (this.currentPage > 1) this.currentPage--;
    },
  },
};
</script>

以上示例展示了 Vue 中实现表格的常见功能,包括基础渲染、动态数据加载、排序和分页。根据实际需求可以进一步扩展功能。

标签: 表格vue
分享给朋友:

相关文章

vue表格实现教学

vue表格实现教学

Vue 表格实现方法 使用原生HTML表格 在Vue模板中直接使用HTML的<table>标签,结合v-for动态渲染数据: <template> <table&g…

vue实现上移下移插件

vue实现上移下移插件

实现上移下移功能的 Vue 插件 在 Vue 中实现列表项的上移和下移功能,可以通过自定义指令或组件封装的方式完成。以下是两种常见实现方式: 基于数组操作的通用方法 通过操作数组索引实现元素位置交换…

vue实现拖放

vue实现拖放

Vue 实现拖放功能 Vue 中实现拖放功能通常可以通过 HTML5 的原生拖放 API 或第三方库(如 vuedraggable)来实现。以下是两种方法的详细说明。 使用 HTML5 原生拖放 A…

vue实现语音

vue实现语音

Vue 实现语音功能的方法 使用 Web Speech API Vue 可以结合 Web Speech API 实现语音识别和合成功能。Web Speech API 包含 SpeechRecognit…

vue实现截图

vue实现截图

Vue 实现截图的方法 使用 html2canvas 库 安装 html2canvas 库: npm install html2canvas 在 Vue 组件中使用: import html2ca…

vue实现遮罩

vue实现遮罩

Vue 实现遮罩层的方法 在 Vue 中实现遮罩层可以通过多种方式完成,以下是几种常见的方法: 方法一:使用 v-show 或 v-if 控制显示 通过 Vue 的指令动态控制遮罩层的显示与隐藏。…