在 Vue 3 中,可以使用计算属性和 watch 来实现分页查询的语法糖。下面是一个简单的示例:

<template>
  <div>
    <ul>
      <li v-for='item in pagedItems' :key='item.id'>{{ item.name }}</li>
    </ul>
    <button @click='previousPage'>Previous</button>
    <button @click='nextPage'>Next</button>
  </div>
</template>

<script>
import { ref, computed, watch } from 'vue';

export default {
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' },
        // ...
      ],
      pageSize: 5,
      currentPage: ref(1),
    };
  },
  computed: {
    pagedItems() {
      const startIndex = (this.currentPage.value - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      return this.items.slice(startIndex, endIndex);
    },
  },
  methods: {
    previousPage() {
      if (this.currentPage.value > 1) {
        this.currentPage.value--;
      }
    },
    nextPage() {
      const totalPages = Math.ceil(this.items.length / this.pageSize);
      if (this.currentPage.value < totalPages) {
        this.currentPage.value++;
      }
    },
  },
  watch: {
    currentPage() {
      // Do something when currentPage changes
      this.fetchData();
    },
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      // Fetch data from backend API based on currentPage and pageSize
    },
  },
};
</script>

在上面的示例中,我们使用了`ref`函数来创建一个响应式的`currentPage`变量。然后,我们使用计算属性`pagedItems`来根据当前页码和页面大小计算出要显示的数据。我们还使用了`watch`来监听`currentPage`的变化,并在变化时执行相应的操作,例如调用`fetchData`方法来从后端API获取数据。

在模板中,我们使用`v-for`指令遍历`pagedItems`数组,并使用`key`属性来保证每个项的唯一性。我们还使用了两个按钮来切换上一页和下一页,分别调用`previousPage`和`nextPage`方法来更新`currentPage`的值。

你可以根据自己的需求修改`fetchData`方法来从后端API获取数据。注意,这只是一个简单的示例,实际应用中可能需要更多的逻辑来处理分页查询。

Vue 3 语法糖实现分页查询:高效且简洁的代码示例