Requirement 1: In a list page, request data when first entered.

Click a list item, jump to the details page, and then back from the details page to the list page without refreshing.

That is, when you go from another page to the list page, you refresh to get the data, and when you go from the details page to the list page, you don’t refresh.

The solution

Settings in app.vue:

    <keep-alive include="list">
        <router-view/>
    </keep-alive>
Copy the code

Suppose the list page is list.vue and the detail page is detail.vue, both of which are child components.

We add the name of the list page in keep-alive and cache the list page.

Then add an Ajax request to the created function of the list page so that the data is requested only when the list page is first entered, and the list page is not refreshed when it jumps from the list page to the detail page and comes back. That should solve the problem.

Requirement 2: On the basis of requirement 1, one more requirement is added: the corresponding list item can be deleted from the detail page. In this case, when you return to the list page, you need to refresh and obtain data again.

We can add a meta attribute to detail.vue on the routing configuration file.

{ path: '/detail', name: 'detail', component: () => import('.. /view/detail.vue'), meta: {isRefresh: true} },Copy the code

This meta property can be read and set in the detail page with this.$route.meta. IsRefresh.

After setting this property, also set the watch $route property in the app. vue file.

watch: { $route(to, from) { const fname = from.name const tname = to.name if (from.meta.isRefresh || (fname ! = 'detail' &&tname == 'list') {from.meta. IsRefresh = false}}Copy the code

}, this eliminates the need for Ajax requests in the created function of the list page, and puts them in app.vue.

There are two conditions for triggering the request data:

When a list comes in from another page (except the details page), you need to request data. When you return from the detail page to the list page, if isRefresh is true in the meta property of the detail page, you also need to re-request the data.

When we remove the corresponding list item from the detail page, we can set isRefresh to true in the meta property of the detail page. Return to the list page and the page will refresh.

If this article is helpful to you, remember to follow me with your fingers