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

Showing the folder based on the URL


When our app mounts, it already calls a function to request the structure for the base
folder. We wrote this function to allow the path to be passed in and, within the created()


function, we have fixed the value to be the root folder of ''. This gives us the flexibility to


adapt this function to pass in the hash from the URL, instead of a fixed string.


Update the function to accept the hash of the URL and, if it doesn't have one, the original


fixed string:


created() {
let hash = window.location.hash.substring(1);
this.getFolderStructure(hash || '');
}

Create a new variable called hash and assign window.location.hash to it. Becuase the


variable starts with #, which is not needed for our app, use the substring function to


remove the first character from the string. We can then use a logical operator to use either


the hash variable, or if that equates to nothing, the original fixed string.


You should now be able to still navigate through your app with the URL updating. If you
press refresh at any time or copy and paste the URL into a different browser window, the


folder you were in should load.


Displaying an error message


With our app accepting URLs, we need to handle a case where someone is entering a URL
and makes a mistake, or a folder is shared that has since been moved.


As this error is an edge case, we are going to hijack the isLoading parameter if there is an


error in loading the data. In the getFolderStructure function, we have a catch function


returned as a promise that gets fired if there is an error with the API call. In this function,


set the isLoading variable to 'error':


getFolderStructure(path) {
window.location.hash = path;
this.dropbox().filesListFolder({
path: path,
include_media_info: true
})
.then(response => {
const structure = {
folders: [],
files: []
Free download pdf