Keep – what is alive

The official resolutionreference
  • Purpose: To solve the problem of maintaining the state of some components when switching components and avoiding the performance problems caused by repeated rendering. (that is, primarily used to preserve component state or avoid rerendering)
Usage scenario of keep-alive

reference

The component wrapped by keep-alive caches the component instance when it is inactive and does not destroy the component. When it is active again, the cached content is read and the component state is saved, without repeatedly requesting the interface to obtain data.

Keep alive – how does it work

Official usereference
<! -- Deactivated components will be cached! --> <keep-alive> <component v-bind:is="currentTabComponent"></component> </keep-alive>Copy the code

Note that

requires that the component being switched to have its own name, either through the component’s name option or through local/global registration.

[heavy] Use of keep-alive in vue-element-admin (Application scenario in my work)

Vue-element-admin uses VUex to centrally manage all components, storing their names in a state called cacheViews. The code is as follows:

<keep-alive :include="cachedViews"> <router-view :key="key" /> </keep-alive> Stored group price by name computed: {cachedViews() {console.log(' Pages added to cache are: ', this.$store.state.tagsView.cachedViews ) return this.$store.state.tagsView.cachedViews }, }Copy the code

** Note that the self-written routing page must have the same name as the state store, otherwise keep-alive will not work. ** indicates that the component to be saved must contain name, which must be the same as cachedViews. The code is as follows:

export default { name: 'organ-category-manage',// stored in cachedViews with the same name, Keep-alive activated() {console.log(' triggers organ-category-manage to fetch data again ', this.dataform)},}Copy the code
More APIS for Keep-Alive

Refer to API on official website

  • props:

    • include– String or regular expression. Only components with matching names are cached.
    • exclude– String or regular expression. Any component with a matching name will not be cached.
    • max– digital. Maximum number of component instances can be cached.
  • Usage:


    when wrapping dynamic components, inactive component instances are cached rather than destroyed. Like
    ,

    is an abstract component: it does not render a DOM element on its own, nor does it appear in the component’s parent chain.

    When a component is switched within

    , its activated and deactivated lifecycle hook functions are executed accordingly.

1. General Usage:

<! Basic -- > - < keep alive - > < component: is = "view" > < / component > < / keep alive - > <! - multiple conditions determine child components -- > < keep alive - > < comp - a v - if = a > "1" > < / comp - > a < comp - b v - else > < / comp - b > < / keep alive - > <! <transition> <keep-alive> < Component :is="view"></component> </keep-alive> </transition>Copy the code

Note that

is used when one of its immediate child components is switched on. If you have v-for in it, it won’t work. If there are multiple conditional child elements,

requires that only one child element be rendered at a time.

2. Include and Exclude prop allow components to cache conditionally. Both can be represented as comma-delimited strings, regular expressions, or an array:

<! -- comma-separated string --> <keep-alive include="a, B ">< Component :is="view"></component> </keep-alive> <! - regular expressions (using ` v - bind `) - > < keep alive: - include = "/ a | b/" > < component: is =" view "> < / component > < / keep alive - > <! - array (using ` v - bind `) - > < keep alive: - include = "(' a ', 'b')" > < component: is = "view" > < / component > < / keep alive - >Copy the code

Matching first checks the name option of the component itself, and if the name option is not available, matches its locally registered name (the key value of the parent component’s Components option). The anonymous component could not be matched.

3. Maximum number of component instances can be cached. Once this number is reached, the cached component instance that has not been accessed for the longest time is destroyed before a new instance is created.

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>
Copy the code

Keep-alive has two important life cycles

  • Activated: When the page is displayed for the first time, the sequence of hooks is created, mounted, and activated

  • Deactivated: Deactivated is triggered when the page exits, but only when the page is moved forward or backward

Keep – the pit of the alive

  • You need to use Actived to directly replace created or Mounted life cycle operations such as sending requests. (However, the issue of Activated does not trigger when pressing F5.)

  • The problem with co-existing both the Created and Actived lifecycles is that the first access triggers both the Created and Actived lifecycles, resulting in the request being sent twice, increasing the strain on the server.

  • If using Actived, remove the Created life cycle. The reason for this is that the forced refresh does not take the actived life cycle, so the request is not sent.

  • The solution to swiping without an Actived life cycle is to add a variable that controls whether the component switches to a first entry or a non-second entry.

    data() { return { firstEnter:false } } created() { this.getDataList() }, Value of activated() {if (this.firstenter) {this.getDatalist ()} else {// If (this.firstenter) { This.firstenter = true}},Copy the code
  • Problems also exist, such as the cache pages have an input box, the box is used to search the data and then apply colours to a drawing to the page, so when input the content in the input box, the switch back a second time would be the executive getDataList actived life cycle method to get the data list, and carry the box. The solution: use two states, one for what the user enters in the input box, and one for the data currently displayed on the page after the user clicks the query button. This saves both user input and the problem of saving component state.

    Data () {return {dataForm: {pageNo: 1, pageSize: 10, keyWord: ",}, keepStateDataForm: {// The status used as a query condition pageNo: 1, pageSize: 10, keyWord: },}} // A unified method to get render data, GetDataList (index) {if (index) {this.dataform. pageNo = index JSON.parse(JSON.stringify(this.dataForm)) } this.dataListLoading = true let params = { pageNo: PageSize: this. Dataform. pageSize, keyWord: This. KeepStateDataForm. KeyWord,} / / send the request to get the data activityInfoList (params). Then (res = > {... })} / * * paging, the method of using getDataList method with parameters carefully, because will be carried out in a state of preservation, pay attention to the status of the save will affect the next data query. You can use the following code to solve the problem of passing pageNo: 'this.dataform. pageNo=1; SizeChangeHandle (val) {this.dataform.pagesize = val this.dataform.pageno = 1 // currentChangeHandle(val) {this.dataform.pageno = val this.getDatalist ()}, reset() { this.dataForm = { pageNo: 1, pageSize: 10, keyWord: '', } this.keepStateDataForm = JSON.parse(JSON.stringify(this.dataForm)) this.getDataList(1) },Copy the code