A discussion on the non-refresh scheme of the forward refresh of Vue single page application

Source: Internet
Author: User

Introduction

Front-end WebApp application in order to pursue a meticulous experience similar to the native pattern, always in the native of the experience, such as the features of this article, native because it is a multi-page application, the new page can enable a new webview to open, Backward is actually closed the current webview, its previous webview is naturally displayed, but in a single page of the WebApp application, all the content is actually displayed in a page, there is no multi-page situation, then the front-end development to find ways to achieve the corresponding experience effect.

First of all, the article said that the forward refresh back does not refresh refers to whether the component is re-rendered, such as the list a page, click on each of them into the details of page B, and then back from the B page to the list a page, a page did not re-render, and did not resend the AJAX request. Next, let's say that in Vue's single page application, the implementation of the forward refresh back does not refresh some of the implementation, other solutions can be added together.

Keep-alive Solutions

Keep-alive is an example of a cache component that is officially provided by Vue, and the usage of the Vue website is described in the following ways:

<keep-alive>When a dynamic component is wrapped, inactive component instances are cached rather than destroyed.

As explained in the Vue website, we can use this in development to cache the routing components that are back without flushing. The concrete realization idea is as follows.

1. Use keep-alive in the template to cache the corresponding routing component

Rewrite in the App.vue template <router-view> , specifically:

<keep-alive>    <router-view v-if="$route.meta.keepAlive">        <!-- 这里是会被缓存的视图组件,比如列表A页面 -->    </router-view></keep-alive><router-view v-if="!$route.meta.keepAlive">    <!-- 这里是不被缓存的视图组件,比如详情B页面--></router-view>

This approach needs to be matched through the Vue routing meta-Information, of course, as follows:

<keep-alive include="A">    <router-view>        <!-- 只有路径匹配到的视图组件,如上面的列表A页面会被缓存! -->    </router-view></keep-alive>

The disadvantages of this approach are:

需要事先知道路由组件的**name**值,这在大型项目中不是一个特别好的选择。
2. Configure routing meta information in the routing configuration file

The following is the first template way to expand the introduction. The following routing metadata is configured in the template file above:

routes: [{        path: ‘/‘,        name: ‘home‘,        component: Home,        meta: {            keepAlive: false //此组件不需要被缓存        }    },    {        path: ‘/list‘,        name: ‘list‘,        component: List,        meta: {            keepAlive: true //此组件需要被缓存        }    },    {        path: ‘/detail‘,        name: ‘detail‘,        component: Detail,        meta: {            keepAlive: false // 此组件需要被缓存        }    }]
3, in the Keep-alive components to provide activatedHook function implements data update logic

It should be emphasized that the keep-alive component (here refers to the routing component of the keep-alive package, the same below) differs from a Vue component, where the specific life cycle function of Vue can be referenced, while keep-alive the component, in addition to the life cycle provided by the normal Vue component, There are 2 additional keep-alive hook functions associated with it:

    • activated: Triggers when cached components are re-entered
    • deactivated: The cached component fires when it leaves

Now that the Keep-alive component provides so many life-cycle function hooks, what are the specific execution sequences of these hook functions?

The first time the Keep-alive component is entered, its life cycle execution order:

beforeRouteEnter --> created --> mounted --> activated --> deactivated

For non-first entry, the order of its life cycle execution:

beforeRouteEnter -->activated --> deactivated

As you can see, the normal Vue component life cycle function is not executed while the Keep-alive component is not first entered, but executes the new two periodic hook function keep-alive. It can also be seen that the destroy periodic function is not executed when leaving the keep-alive component, and the side proves that the cache component is not destroyed. According to the introduction, we can:

By using keep-alive to provide a activated hook function to decide whether to make an AJAX request to update the component, and the deactivated hook function to reset the page-related state.

Keep-alive implementation of the post-push does not refresh the scheme, there are some places need special attention:

    • Keep-alive components update time to have a clear understanding of

This means that in the development process it is necessary to know that the back does not refresh the component although it is not re-rendered, but to know under what circumstances the component data needs to resend the AJAX request to fetch the data, thus updating the component.

Taking the A and B pages above, we need to know when the keep-alive component of the list a page is updated, since the entry to page a can be either backwards from page B or forward from another page, which, of course, requires a distinction between the two different situations. Otherwise, the data on page A is always the first cached data.

This article gives a solution:

First, add a isback field to each routing meta-information meta to resolve that Beforerouterenter cannot access the Vue instance directly.

    ...    {        path: ‘/list‘,        name: ‘list‘,        component: List,        meta: {            keepAlive: true, //此组件需要被缓存            isBack: false        }    }    ...

Then, use the beforeRouteEnter hook function to determine the page source:

    beforeRouteEnter(to, from, next) {      if(from.name === ‘detail‘) { //判断是从哪个路由过来的,若是detail页面不需要刷新获取新数据,直接用之前缓存的数据即可          to.meta.isBack = true;      }      next();    },

Finally, you need to use keep-alive to provide a hook function activated to complete the update:

  activated() {    if(!this.$route.meta.isBack) {      // 如果isBack是false,表明需要获取新数据,否则就不再请求,直接使用缓存的数据      this.getData(); // ajax获取数据方法    }    // 恢复成默认的false,避免isBack一直是true,导致下次无法获取数据    this.$route.meta.isBack = false  },
    • page refresh in the Keep-alive component causes Keep-alive component state to be lost

Continue to the above a, B page for example, after entering the detail B page, and then refresh, then the list a page of the cached data is lost, because the above rules will also cause the data will not be retrieved. So for this kind of problem, we need to add some additional judgment condition. Since Keep-alive executes the created method The first time it enters, it is judged using this plus an identity:

   //第一次进入keep-alive路由组件时    created() {      this.isFirstEnter = true;     // 只有第一次进入或者刷新页面后才会执行此钩子函数,使用keep-alive后(2+次)进入不会再执行此钩子函数   },

The activated hook function also needs to increase the corresponding judgment:

  activated() {     if(!this.$route.meta.isBack || this.isFirstEnter){         // 如果isBack是false,表明需要获取新数据,否则就不再请求,直接使用缓存的数据         // 如果isFirstEnter是true,表明是第一次进入此页面或用户刷新了页面,需获取新数据         this.data = ‘‘// 把数据清空,可以稍微避免让用户看到之前缓存的数据         this.getData();     }     // 恢复成默认的false,避免isBack一直是true,导致下次无法获取数据     this.$route.meta.isBack=false     // 恢复成默认的false,避免isBack一直是true,导致每次都获取新数据     this.isFirstEnter=false;   },
    • Cache too many keep-alive components due to resident memory causing excessive memory consumption

This is a particularly important issue, especially when the entire system or system most pages use Keep-alive to cache components, because they are cached in memory, if not processed, memory accumulation is increasing, resulting in the system. The correct solution is to destroy the components of the memory cache in a timely manner .

Specific can refer to: Vue issue#6509 and remember the keep-alive of Vue, two articles of the way to realize the idea.

Nested routines by

Embedded routines by the specific implementation can refer to the official website, this is a solution to the idea. Here is a concrete example, as shown, to illustrate the implementation process.

As shown, an order page has 6 pages that jump out of the current page to view rules, protocols, or pages that modify specific content, because these 6 items depend on this page, then you can use route nesting to implement this fallback non-flush process, the next single page as the parent route, and the other jump items to be their child routes. Specific steps:

1. Configure Routing information
    {      path: ‘/order‘,      component: Order,      children: [        {          path: ‘invoice‘,          component: Invoice        }, {          path: ‘contact‘,          component: Contact        },        {          path: ‘costrule‘,          component: CostRule        }, {          path: ‘refundrule‘,          component: RefundRule        },{          path: ‘useragreement‘,          component: UserAgreement        },{          path: ‘payrule‘,          component: PayRule        }      ]    }
2, the next single page OrderConfigure route nesting in the component template.
    <div class="safe-area-pb">     <purchase />     <router-view />        </div>                  

In this way, through the next page to enter other pages, such as access to modify the contact information page, then the route from /order to /order/contact, after the completion of the modification of the rollback will return to the parent route /order , After the completion of the push does not refresh the feature.

Of course, as mentioned above, the nesting scheme is only an optional scheme, with its corresponding usage scenarios, and the following points need to be noted in the use process:

**1, after the sub-route, if the child route is forced flush, the parent-child routed component will be re-rendered, the life cycle of the respective routing component is performed, and the related logic in the parent route executes.

**2, Zi Lu by other pages, when entering the sub-route will trigger the 1th situation, so the best sub-route is the parent Route exclusive.

Component Component with routing scheme

This scheme is mainly implemented by using the dynamic routing component component provided by Vue, which is no longer determined by the routing path, but the different dynamic components are loaded according to different business logic. The specific implementation can refer to this article solution in the 6th part: How to dynamically register a route with an async-loaded line of business? Similarly, a synchronous route can use dynamic routing to complete a backward-not-refresh function. This is a much more restrictive use scenario in this way.

Summarize

The above 3 solutions, the first one is familiar, the latter two may be relatively unfamiliar. They are just different solutions to the same problem, presumably there are other solutions I did not think that there are other better solutions can be explored together.

Reference

1. Drip WebApp 5.0 Vue 2.0 Reconstruction experience sharing
2, Alternative: Vue single page, multi-route, forward refresh, back not refreshed
3. The keep-alive of Vue-router
4, remember once Vue's keep-alive trample the road of the pit
5, Hope keep-alive can increase the ability to dynamically delete the cached components

A discussion on the non-refresh scheme of the forward refresh of Vue single page application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.