Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Pre-Caching Other Folders and Files for Faster Navigation Chapter 7

If we add a console log to the function of the parent's variable, we can see it contains the


folders we now wish to cache. We can now loop through this array, calling the cache


function for each item in the array:


mounted() {
let parents = this.folders;
parents.reverse().shift();

for(let parent of parents) {
this.cache(parent.path);
}
}

With this, our parent and child folders are being cached by the app, making navigation


both up and down the tree lightning fast. However, running a console.log() inside the


mounted function reveals the breadcrumb gets re-mounted every time a folder gets


navigated to. This is because of the v-if statements in the View, which removes and adds


the HTML each time.


As we only need to cache the parent folders once, on initial app load, let's look at changing


where it gets triggered. We only need to run this function the first time; once the user has
started navigating up and back down the tree, all the folders visited will be cached along


the way.


Caching parent folders once


To ensure we are using the least amount of resources, we can keep the array of folders used
for the breadcrumb in the store. This means that both the breadcrumb component and our


parent caching function can access the same array.


Add a breadcrumb key to your store state—this is where we will store the array:


const store = new Vuex.Store({
state: {
path: '',
structure: {},
breadcrumb: []
},
mutations: {
updateHash(state) {
let hash = window.location.hash.substring(1);
state.path = (hash || '');
},
structure(state, payload) {
Free download pdf