Introduction:
In our previous post, 'Vue.js: Build Simple Tabs with Dynamic Components' we explored creating basic tabs with dynamic components. But what if we need to fetch data from the server for each tab? What if this data needs to be updated selectively upon tab activation? Join me in this post as we delve into the intricacies of fetching server data for dynamic tabs and explore the functionality of the 'KeepAlive' component. Let's unravel the complexities together...
We will not dive deep into how to start a new project, or how to build tabs, as I mentioned you can find it in my previous post 'Vue.js: Build Simple Tabs with Dynamic Components'. Here we will start from already existing tabs and step 4.
Step 4: Fetch and render data.
We will use Free Fake API for testing 'JSON Placeholder'. There is a cool endpoint for us 'https://jsonplaceholder.typicode.com/photos' that returns a list of images with descriptions, but also we can add an ID and receive only one image.
In our Tab.vue component in the created hook, let's generate a random integer number to fetch different images every time our tab was created, then asynchronously fetch the photo and store it in the 'photo' variable. After the photo is successfully received it will be rendered in our Tab component. We will add this functionality to all our Tabs, and every time the active Tab changes new image will be shown. Here is the Tab.vue code example:
Let's start our project 'npm run serve' and check the result:
It looks great, our tabs work correctly. Also, we can check fetched data in Vue.js dev tools in the browser window.
Return a few times to the same tab and the image will be updated. It's useful if we update data in the server often, and need to fetch and rerender it in our app. But what if we need to receive it once? Or what if we care about our server resources? Not a big deal, because we have a component.
Step 5. component.
Okay, let's wrap out the dynamic component into the component and check what changed.
Everything works fine, but when you change the tab and return to the previous it will not send the request to the server for data, because thankfully to component tab was not destroyed and it still stores data. You can check it in Dev tools, tabs still exist but some of them are just inactive.