使用Vue.js實作帶有查詢字串的網站分頁功能
P粉809110129
P粉809110129 2024-02-17 13:49:04
0
1
360

在主頁中,我有一個容器,其中顯示一些元素,下面有一個包含所有頁面(1、2、3、4...)的分頁,分頁正在工作。但是,我想在我的網址中新增查詢,因此如果輸入類似 http://localhost:8080/twity/?page=10 的內容,我想前往該頁面。我正在添加這樣的查詢,但它只顯示我所在的當前頁面的編號,如果我更改網址中的編號,它只會將我返回到第一個(預設)頁面...

this.$router.push({ query: { page: this.currentPage } })

如果需要,我可以分享我的整個 Home 元件程式碼。謝謝。

主頁元件

<template>
  <div class="main">
    <div class="tweets-container">
      <div
        v-for="tweet in tweets"
        :key="tweet.id"
      >
        <div class="tweet-card">
          <div class="username-time">
            <div class="user-info">
              <p class="name">
                {{ tweet.twitter_name }}
              </p>
              <p class="user-info-p">
                @
              </p>
              <p class="username">
                <a
                  :href="'https://twitter.com/' + tweet.twitter_username"
                  class="twitter_link"
                  target="_blank"
                >
                  {{ tweet.twitter_username }}
                </a>
              </p>
            </div>
            <div class="time">
              <p>{{ tweet.added_at }}</p>
            </div>
          </div>
          <div class="text">
            <p>{{ tweet.tweet_text }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="reply-container">
      <h1>Replies</h1>
    </div>
    <ul class="pagination">
      <li class="page-item">
        <p
          class="hover-underline-animation"
          @click="previousPage"
        >
          Previous
        </p>
      </li>
      <li class="page-item all-pages">
        <div
          v-for="page in numberOfPages"
          :key="page"
          :class="page == currentPage ? 'active' : 'hover-underline-animation'"
          @click="getTweets(page)"
        >
          <p>{{ page }}</p>
        </div>
      </li>
      <li class="page-item">
        <p
          class="hover-underline-animation"
          @click="nextPage"
        >
          Next
        </p>
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'
import { getUserToken } from '@/auth/auth'
import moment from 'moment'

export default {
  components: {},
  data() {
    return {
      tweets: [],
      currentPage: 1,
      numberOfPages: 0,
    }
  },
  beforeMount() {
    this.getTweets()
  },
  methods: {
    nextPage() {
      this.currentPage += 1
      this.tweets = []
      this.getTweets()
    },
    previousPage() {
      this.currentPage -= 1
      this.tweets = []
      this.getTweets()
    },
    getTweets(newCurrent) {
      this.tweets = []
      const API_URL = `${this.$server}/api/twitter/tweets`
      const params = {
        token: getUserToken(),
        page: this.currentPage,
        newCurrentPage: newCurrent,
      }
      axios.post(API_URL, null, { params }).then(res => {
        this.currentPage = res.data.page
        this.numberOfPages = res.data.numberOfPages
        // Set query string
        this.$router.push({ query: { page: this.currentPage } })

        res.data.tweets.forEach(tweet => {
          const tweetData = {
            id: tweet.id,
            tweet_text: tweet.tweet_text,
            twitter_name: tweet.twitter_name,
            twitter_username: tweet.twitter_username,
            added_at: moment(String(tweet.added_at)).format('MM/DD/YYYY hh:mm'),
          }
          this.tweets.push(tweetData)
        })
      })
    },
  },
}
</script>

Nodejs函數(用於從資料庫取得資料並控制分頁)

getAllTweets: async (req) => {
        // get number of all rows in table
        let tweetsNum = await SQL('SELECT COUNT(*) as total FROM twitter_tweets')
        tweetsNum = tweetsNum[0].total

        // number of tweets
        const pageSize = 25
        let skip = 0

        const numberOfPages = Math.ceil(tweetsNum / pageSize)

        // page number from client
        const newCurrentPage = req.query.newCurrentPage
        let currentPage = req.query.page
        
        // check if there is newCurrentPage
        if(newCurrentPage != undefined) {
            skip = (newCurrentPage - 1) * pageSize
            currentPage = newCurrentPage
        } else {
            // check if page is valid)
            if(currentPage < 1) {
                currentPage = 1
            } else if(currentPage > numberOfPages) {
                currentPage = numberOfPages
            }
            
            // offset
            skip = (currentPage - 1) * pageSize
        }

        // paginate tweets from db
        const tweetsFromDb = await SQL('SELECT * FROM twitter_tweets ORDER BY added_at DESC LIMIT ?,?', [skip, pageSize])

        let tweets = Object.values(JSON.parse(JSON.stringify(tweetsFromDb)))

        const data = {
            tweets: tweets,
            page: parseInt(currentPage),
            numberOfPages: parseInt(numberOfPages),
        }

    return data
}

P粉809110129
P粉809110129

全部回覆(1)
P粉998100648

    beforeRouteUpdate(to,from,next) {
      yourFunctionXXXXX(to.query);
      next();
   },

 beforeRouteEnter(to, from, next) {
         next((vm) => {
            vm.yourFunctionXXXXX(to.query);
       });
  },
你應該先使用路由預衛來攔截你的路由參數,然後根據參數手動決定你應該顯示什麼內容
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板