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

If we wanted to display a divider between the folder names, such as a slash or chevron, this


can be easily added. However, a slight hurdle arises when we want to display the separator
between the links, but not at the beginning or end. To resolve this, we are going to utilize


the index keyword available when doing a loop. We are then going to compare this against


the length of the array and operate a v-if declaration on an element.


When looping through an array, Vue allows you to utilize another variable. This, by
default, is the index (the position of the item in the array); however, the index may be set to


a value if your array is constructed in a key/value fashion. If this is the case, you can still
access the index by adding a third variable. As our array is a simple list, we can easily use


this variable:


template: '<div>' +
'<span v-for="(f, i) in folders">' +
'<a :href="f.path">{{ f.name || 'Home' }}</a>' +
'<span v-if="i !== (folders.length - 1)"> »
</span>' +
'</span>' +
'</div>',

Update the f variable to a pair of brackets containing an f and an i, comma separated. The


f variable is the current folder in the loop, while the i variable that has been created is the


index of the item. Bear in mind that the array indexes start at 0 instead of 1.


The separator we've added is contained in a span tag with a v-if attribute, the contents of


which could look confusing. This is confusing the current index with the length of the


folders array (how many items it has) minus 1. The - 1 is because of the index starting at


0 and not 1, as you would expect. If the numbers do not match, then the span element is


displayed.


The last thing we need to do is make our breadcrumb navigate to the selected folder. We


can do this by adapting the navigate function we wrote for the folder component.


However, because our whole component is the breadcrumb and not each individual link,
we need to alter it so it accepts a parameter.


Start off by adding the click event to the link, passing in the folder object:


template: '<div>' +
'<span v-for="(f, i) in folders">' +
'<a @click.prevent="navigate(f)"
:href="f.path">
{{ f.name || 'Home' }}</a>' +
'<i v-if="i !== (folders.length - 1)"> »
</i>' +
'</span>' +
Free download pdf