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

(singke) #1
Caching the Current Folder Structure Using Vuex Chapter 6

Although this works as is, it would be good practice to sanitize the path when using it as


the key in an object. To do this, we are going to remove any punctuation, replace any
spaces and slashes with hyphens, and change the path to lowercase.


Create a new computed function called slug on the dropbox-viewer component. The


term slug is often used for sanitized URLs and originates from newspapers and how editors


used to reference stories. This function will run several JavaScript replace methods to


create a safe object key:


slug() {
return this.path.toLowerCase()
.replace(/^\/|\/$/g, '')
.replace(/ /g,'-')
.replace(/\//g,'-')
.replace(/[-]+/g, '-')
.replace(/[^\w-]+/g,'');
}

The slug function carries out the following operations. An example path of


/images/iPhone/mom's Birthday - 40th would be affected in the following way:


Convert the string to lowercase: /images/iphone/mom's birthday - 40th
Remove any slashes at the beginning and end of the path: images/iphone/mom
birthday - 40th
Replace any spaces with hyphens: images/iphone/mom-birthday---40th
Replace any slashes with hyphens: images-iphone-mom-birthday---40th
Replace any multiple hyphens with just a singular hyphen: images-iphone-
mom-birthday-40th
Finally, remove any punctuation: images-iphone-moms-birthday-40th

With the slug now created, we can use this as the key when storing the data:


this.$store.commit('structure', {
path: this.slug,
data: response
});

With our folder contents now being cached in the Vuex store, we can add a check to see
whether the data exists in the store and if it does, load it from there.

Free download pdf