搜索

首页  >  问答  >  正文

使用Vue.js实现带有查询字符串的网站分页功能

在主页中,我有一个容器,其中显示一些元素,下面有一个包含所有页面(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粉809110129P粉809110129286 天前367

全部回复(1)我来回复

  • P粉998100648

    P粉9981006482024-02-18 00:55:26

        beforeRouteUpdate(to,from,next) {
          yourFunctionXXXXX(to.query);
          next();
       },
    
     beforeRouteEnter(to, from, next) {
             next((vm) => {
                vm.yourFunctionXXXXX(to.query);
           });
      },
    你应该先使用路由预卫来拦截你的路由参数,然后根据参数手动决定你应该显示什么内容

    回复
    0
  • 取消回复