Luca Rossi
Luca Rossi

Reputation: 776

Avoid fetching images everytime page load - vuejs

I'm building a page that show dynamically some photos in a feed like Instagram. I'm getting stuck trying to avoid everytime I load a page or I go into a photo's detail page and then go back, to do an API request to Laravel controller, so that means fetching data and images, losing the position of the page and starting on the top of the page.

My code:

Feed.vue

<template>
<div v-for="(image, index) in images" :key="index">
   <v-img :src="image.path" class="image-masonry mini-cover" slot-scope="{ hover }"></v-img>
</div>
</template>

<script>
export default {
    data() {
    return {
      images: []
    }
  },
  mounted() {
    this.getImagesHome();
  },
  methods: {
    getImagesHome() {
      this.axios.get('/api/images', {},
        ).then(response => {
          this.images = response.data;
        }).catch(error => {
          console.log(error);
      });
    },
  }
}
</script>

Edit:

I saw that keep-alive is primarily used to preserve component state or avoid re-rendering it. But i can't understand how to use it. I call my Feed.vue component in another Home.vue as below:

<template>
  <v-app>
    <Toolbar @toggle-drawer="$refs.drawer.drawer = !$refs.drawer.drawer"></Toolbar>
    <Navbar ref="drawer"></Navbar>
    <keep-alive>
      <Feed></Feed>
    </keep-alive>
  </v-app>
</template>

<script>
  import store from '../store';

  export default {
    components: {
      'Toolbar' : () => import('./template/Toolbar.vue'),
      'Navbar' : () => import('./template/Navbar.vue'),
      'Feed'   : () => import('./Feed.vue')
    }
  }
</script>

What i have to put more in keep-alive and what i have to change in my Feed.vue component?

Upvotes: 2

Views: 2044

Answers (1)

S.B
S.B

Reputation: 847

mounted() should only be called once.

There seem to be multiple ways to go about this.

  1. If you are using vue-router, then have a look at scrollBehaviour

https://router.vuejs.org/guide/advanced/scroll-behavior.html

From their documentation,

  const router = new VueRouter({
    routes: [...],
    scrollBehavior (to, from, savedPosition) {
      // return desired position
    }
  })


You can also try using keep-alive: https://v2.vuejs.org/v2/api/#keep-alive

It keeps the component in memory so it is not destroyed, you get activated and deactivated events to check when it comes into view.

But I don't think it saves scroll position, so you may want to use this in combination with scrollBehaviour

Upvotes: 1

Related Questions