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

(singke) #1
Navigating through the File Tree and Loading Folders from the URL Chapter 5

We are already inside both single and double quotes, so we need to inform JavaScript


we literally mean a single quote and this is done by using a backslash in front of the single
quote character:


Vue.component('folder', {
template: '<li><strong><a :href="\'#\' +
f.path_lower">{{ f.name }}</a></strong></li>',
props: {
f: Object
}
});

We can also remove the @path attribute from the component in the view:


<template v-for="entry in structure.folders">
<folder :f="entry"></folder>
</template>

Already our code is looking cleaner, less cluttered, and smaller in file size. Viewing the app


in the browser will render the structure of the folder you are in; however, clicking links will
update the URL but not change what is displayed.


Updating the structure with a URL change and setting

Vue data outside of the instance

Now that we have our URL updating correctly, we can get the new structure whenever the


hash changes. This can be done natively with JavaScript with the onhashchange function.


We are going to create a function that fires whenever the hash of the URL updates, which,
in turn, will update a path variable on the parent Vue instance. This variable will be passed


to the child dropbox-viewer component as a prop. This component will be watching for a


change in the variable and, upon update, it will retrieve the new structure.


To begin with, update the parent Vue instance to have a data object with a path key - set to


the empty string property. We are also going to assign our Vue instance to a constant
variable of app—this allows us to set data and call methods outside of the instance:


const app = new Vue({
el: '#app',

data: {
path: ''
}
});
Free download pdf