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

This API method accepts an object, similar to the filesListFolder function. We're


passing the path of the current file. Once the data is returned, we can set the component's


link attribute to the download link.


We can now add a download link to the template of the component. Add a v-if to only


show the once the download link has been retrieved:


template: '<li><strong>{{ f.name }}</strong><span v-
if="f.size"> - {{ bytesToSize(f.size) }}</span><span
v-if="link"> - <a :href="link">Download</a></span>
</li>'

Browsing through the files, we can now see a download link appearing next to each file, the


speed of which will depend on your internet connection and the API speed.


The full file component, with the download link added, now looks like:


Vue.component('file', {
template: '<li><strong>{{ f.name }}</strong><span v-
if="f.size"> - {{ bytesToSize(f.size) }}</span><span
v-if="link"> - <a :href="link">Download</a></span>
</li>',
props: {
f: Object,
d: Object
},
data() {
return {
byteSizes: ['Bytes', 'KB', 'MB', 'GB', 'TB'],
link: false
}
},
methods: {
bytesToSize(bytes) {
// Set a default
let output = '0 Byte';
// If the bytes are bigger than 0
if (bytes > 0) {
// Divide by 1024 and make an int
let i = parseInt(Math.floor(Math.log(bytes) /
Math.log(1024)));
// Round to 2 decimal places and select the
appropriate unit from the array
output = Math.round(bytes / Math.pow(1024, i), 2)
+ ' ' + this.byteSizes[i];
}
return output
← Previous
Free download pdf