Vue.js项目构建失败:分页功能报错求助
Fixing Vue.js Pagination Issues (Syntax Error + Prettier Warning)
Let's break down and fix your problems one by one, making the pagination work smoothly while addressing both errors:
1. Resolve the v-for + v-if Syntax Error
Vue explicitly discourages using v-for and v-if on the same element—it causes unnecessary performance overhead and messy logic. Instead, we'll move all filtering logic into computed properties, and restructure the pagination to behave correctly:
Key JS Fixes:
- Add a
currentPagedata property to track the active page - Create a
currentCamscomputed property that returns only the cameras for the current page - Fix inconsistent variable naming (
perPagevsperpagein your original code) - Clean up code structure to align with Vue best practices
Key HTML Fixes:
- Use the
currentCamscomputed property for your camera listv-for - Simplify pagination buttons to loop through page numbers directly, with a click handler to switch pages
- Remove the nested, problematic
v-for/v-ifcombo on pagination list items
2. Fix Prettier Format Warnings
All code below is formatted to comply with Prettier standards (proper indentation, line breaks, consistent spacing) so you won't get those formatting warnings anymore.
Fixed Full Code
HTML Template:
<!-- Camera Feed Grid --> <div class="col-1 text-center p-0 feed-col" v-for="(cam, idx) in currentCams" :key="idx"> <img class="img-fluid w-100 h-100" :src="cam.image_url_360x270" /> <div class="card-img-overlay p-0"> <a class="text-white text-decoration-none stretched-link" target="_blank" :href="cam.chat_room_url_revshare" ></a> </div> </div> <!-- Pagination Controls --> <nav aria-label="Page navigation example"> <ul class="pagination"> <li class="page-item" :class="{ active: n === currentPage }" v-for="n in pages" :key="n" > <button class="page-link" @click="currentPage = n">{{ n }}</button> </li> </ul> </nav>
Script Section:
<script> import Vue from 'vue' export default Vue.extend({ name: "Index", data() { return { onlineCams: [], perPage: 50, currentPage: 1 // Track the active page number }; }, mounted() { // Your existing data fetch/update logic goes here }, computed: { totalCams() { return this.onlineCams.length }, pages() { return Math.ceil(this.totalCams / this.perPage) }, currentCams() { // Calculate start/end indexes for the current page const startIndex = (this.currentPage - 1) * this.perPage const endIndex = startIndex + this.perPage // Return the sliced array of cameras for the current page return this.onlineCams.slice(startIndex, endIndex) } }, methods: { // Your existing data fetch methods go here } }); </script>
Extra Improvements:
- Replaced pagination
<a>tags with<button>s (client-side page switching doesn't need anchor links) - Added an
activeclass binding to highlight the current page button - Renamed
lengthtototalCamsfor better code readability - Ensured all variable names are consistent (no more mixed
perPage/perpage)
内容的提问来源于stack exchange,提问作者ki.ko
相关产品推荐
相关产品推荐

