Vue realizes the effect of forward refresh and backward refresh

  Front end, javascript, vue.js

More articles

Requirement 1:

In a list page, the first time you enter, you request to obtain data.
Click on a list item, jump to the details page, and then go back to the list page from the details page without refreshing.
In other words, if you enter the list page from other pages, you need to refresh to obtain data, and do not refresh when you return from the details page to the list page.


        <keep-alive include="list">

Suppose the list page islist.vueThe details page isdetail.vue, both of which are subcomponents.
We arekeep-aliveAdd the name of the list page and cache the list page.
Then on the list pagecreatedFunction to add ajax requests, so that data will only be requested when entering the list page for the first time. When jumping from the list page to the detail page and returning from the detail page, the list page will not refresh.
This will solve the problem.

Requirement 2:

On the basis of requirement 1, add another requirement: you can delete the corresponding list item in the details page, and then you need to refresh and retrieve the data when returning to the list page.
On the routing profile, we candetail.vueAdd onemetaProperty.

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

This ..metaProperty, which can be passed in the details pagethis.$route.meta.isRefreshTo read and set.
After setting this propertyApp.vueSet watch in the file$routeProperty.

    watch: {
       $route(to, from) {
           const fname =
           const tname =
           if (from.meta.isRefresh || (fname != 'detail' && tname == 'list')) {
               from.meta.isRefresh = false
                   // 在这里重新请求数据

This eliminates the need for acreatedFunction to request data with ajax, unified inApp.vueIn order to deal with.
There are two conditions for triggering request data:

  1. Data needs to be requested when entering the list from other pages (except the details page).
  2. When returning from the details page to the list page, if the details pagemetaThe in the propertyisRefreshFortrue, also need to request data again.

When we delete the corresponding list item in the detail page, we can transfer the detail pagemetaThe in the propertyisRefreshSet totrue. Then return to the list page and the page will be refreshed again.