当前位置:首页 > VUE

用vue实现表格

2026-03-08 13:09:12VUE

使用 Vue 实现表格

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

基础表格实现

创建一个 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 加载数据:

<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>

添加分页功能

通过计算属性实现分页:

用vue实现表格

<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 实现跑车动画效果 使用 Vue 结合 CSS 动画可以实现跑车在屏幕上移动的效果。以下是一个完整的实现方案: 创建 Vue 组件结构 <template> <div c…

vue实现切换

vue实现切换

Vue 实现切换功能的方法 在 Vue 中实现切换功能可以通过多种方式实现,以下是一些常见的方法: 使用 v-if 和 v-else 指令 通过条件渲染实现切换功能,适用于简单的显示/隐藏场景。…

vue实现ajax

vue实现ajax

Vue 中实现 AJAX 的几种方法 在 Vue 中实现 AJAX 请求可以通过原生 JavaScript 的 XMLHttpRequest、第三方库如 axios 或 fetch API 来完成。以…

vue computed实现

vue computed实现

计算属性的基本用法 在Vue中,计算属性通过computed选项定义,用于声明依赖于其他属性的动态值。计算属性基于它们的依赖进行缓存,只有依赖发生变化时才会重新计算。 new Vue({ dat…

vue实现绘图

vue实现绘图

Vue 实现绘图的方法 在 Vue 中实现绘图功能,可以通过多种方式实现,包括使用原生 HTML5 Canvas、第三方库(如 Fabric.js、Konva.js)或 SVG。以下是几种常见的实现方…

vue实现音乐

vue实现音乐

Vue实现音乐播放功能 使用Vue实现音乐播放功能可以通过多种方式完成,以下是几种常见的实现方法: 使用HTML5 Audio API 在Vue组件中直接使用HTML5的Audio对象来控制音乐播放…