This is the 4th day of my participation in the August More Text Challenge

Vue multi – page cache implementation

As we all know, VUE is a single page route. We usually use keep-alive to wrap route-View during page caching, so that data can be cached.

preface

The caching pattern

<keep-alive>
  <router-view></router-view>
</keep-alive>
Copy the code

The toggle does not re-execute the life cycle only after the first render of the current route, and can cache router-view data.

Router-view data cache problem

Keep-alive uses the render function to create a Vnode, render is used to obtain the Vnode, if cache[key] exists, then:

vnode.componentInstance = cache[key].componentInstance
Copy the code

Otherwise, store the Vnode in the cache:

cache[key] = vnode
Copy the code

The body of the

I. Left menu: open page TAB (red box), display part of page content window (green box)

Define attributes in the project root instancePoint to theThe latest keep-alive data of the project

Note: The above code has realized the project keepalive data stored in the VUE instance, when closing the page, clear the corresponding data can be;

Iii. Page closing processing, the code is as follows:

Note: Click close TAB, call close event, close then delete TAB data, and then delete page keepalive data (clearVmNode function); ClearVmNode function, according to the path in the TAB data to be closed to find the corresponding page in the keepalive data virtual DOM cache data, and then delete;

Four, vUE dynamic routing page want to carry out the corresponding page data cache according to the address bar

Note: If the above is not processed, then only one copy of keepalive page data cache is stored, and only one copy of page virtual DOM data is stored when ID is 63 and 65, and two copies are needed here. The implementation code is as follows: (left is before the change, right is after the change)

Note: the source code is used as name storage virtual DOM data identification, the name is. Vue name attribute, so in order to cause dynamic routing only a cache of data, we only need to use the page path to do the unique identification of the storage page data;

This is all the code to use keep-alive to implement multiple page caching, thanks for watching! Review the past and learn the new!