bailboo
bailboo

Reputation: 49

How to save page number in url path when leaving page in Vuejs

I have posted a couple times and always struggling with vuejs as i am learning on the fly.

I created a page that lists articles/blog posts and then paginated it. When you click page 2, i have the url change to show you are on page 2. The problem i am having is if you click an article on page two and either press back or click a button i added to the article to bring you back to the list of articles, it doesn't save the page number. Now, i understand that i have my default "currentPage" set to 1, but i don't know how to set it so it doesn't grab the default. All of my code is in one page, not a full vue application.

const routes = [
   {
     name: 'news',
     path: '/:currentPage',
     component: vueApp
   }
]
    
 const router = new VueRouter({
     routes
 })
    
 var vueApp = new Vue({
    router,
    el: '#news-wrapper',
    data: function data() {
      return {
        filteredArticles: [],
        timer: null,
        currentPage: 1,
        perPage: 10,
        pages: [],
        articles: [ array ]
   }
 },
 updated: function updated() {
    var page = this.currentPage;

    this.$router.replace({ name: 'news', params: {currentPage: this.currentPage}})
}

As you can see, I have the router grabbing currentPage and that is also in my data set to 1. Do i need to create a new value ? I need it save the page I am on even if i leave the page and come back, or even just refresh the page. Any help would be appreciated.

Let me know if you more of my code is needed!

Upvotes: 1

Views: 722

Answers (1)

scar-2018
scar-2018

Reputation: 528

If the initial value of currentPage is set with the value from the url, then the problem can be solved. How can we set the initial value then?

Here is my approach.

 var vueApp = new Vue({
   router,
   el: '#news-wrapper',
   data: function data() {
     return {
       filteredArticles: [],
       timer: null,
       currentPage: this.$route.params.currentPage || 1,
       perPage: 10,
       pages: [],
       articles: [ array ]
   }
 }

Upvotes: 3

Related Questions