}

Vue.js: How to show first and last element of an array in templates

Created:

Introduction

When using Vue.js sometimes you want to show the first (or last) element of an array. In some other use cases you wan to know if you are on the so you can close the html tags.

For example suppor you hace a list of cars:

$cars = [ 'red car', 'blue car', 'green car'];
<template v-for="car in cars">
    {{ car }}<span v-if="! loop.last">, </span><span v-if="! loop.last">.</span>
</template>

Be careful with this code since it will compare element using =!, ig you use ==! the "last" idea will not work.

Extend Vue.js prototype by addign $last

You can just extend Vue.js to support last item by usign this code:

Vue.prototype.$last = function (item, list) {
  return item === list[list.length - 1]
}

On your templates you can use it now:

<span v-if="!$last(author, authors)">...</span>