简体   繁体   中英

Vue.js merge data without a re-render?

I have a search component that gets its data in the form as a prop of PHP json_encoded data:

<search :data="<?= json_encode($jsonHotels) ?>"></search>

This way it receives the first 25 movies straight away when the page renders.

After this I make an ajax request to fetch the rest of the result if there are more than 25 movies.

The problem is that when I override the data with the data from the AJAX call, the component re-renders.

Previously to combat this I performed an ajax request with an offset of 25 to skip the first 25 movies and only give me the extra results. Pushing this onto the array didn't cause a re-render and this worked perfectly.

That was perfect, until I got to thinking:

What about people who start or refresh the page while they are on page number 2-3-4-5-etc.

I now have to not only mess with my offset, but I also have to possibly prepend data to my array and well as possibly append data with a push.

Is there a way to merge data without causing a re-render? I am wondering if anyone else has every run into the problem.

Simply fetching all results with an AJAX request takes too long and obviously also causes a re-render. Not fetching initial backend data would mean people would be starting at a blank page or a spinner for 2-3 seconds.

Edit:

Ended up with this:

mergeData(state) {
    // Smart merge ajaxData and hotels.
    const offSet = state.currentPage * state.itemsPerPage;

    const start = state.ajaxData.slice(0, offSet - state.itemsPerPage);
    const end = state.ajaxData.slice(offSet);

    state.data.unshift(...start);
    state.data.push(...end);
},

Pretty much slice my array in 2 and remove the currentPage section. By using unshift and push I prevent a re-render from happening.

Remember that your viewmodel is a model of your view. Here, you're not modeling your application, you're just trying to plug your data in.

If you want to display a page of results at a time, have some kind of model for a page of results. When you fetch your data, put it into the appropriate model-pages. Since you're only displaying one page at a time, populating other pages will not cause a re-render.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM