More articles

Requirements:

In a list page, the first time you enter, request data. 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.

Solution set 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, another requirement is added: the corresponding list item can be deleted in the detail page, and then the data needs to be refreshed when returning to the list page. 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:

  1. When a list comes in from another page (except the details page), you need to request data.
  2. Return from the details page to the list page if the details pagemetaProperties of theisRefreshtrue, also needs to rerequest 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.