What is the best way to add a new tag in between each pair of tags generated by v-for?

Is there a way I can add a new element between every two items generated by v-for in Vue.js, similar to using Array.join()?

Background:

I would like to insert a <span>,</span> between every pair of

<router-link></router-link>
.

The

<router-link></router-link>
elements are created dynamically using v-for, as shown below:

<router-link tag="a" 
             v-for="text in ['vue', 'react', 'JQuery']"
             :key="text"
>
  {{ text }} &nbsp;
</router-link>

When rendered, the output looks like this:

vue react JQuery

In order to achieve the desired structure, I had to enclose the elements within a <div>:

<div v-for="text in ['vue', 'react', 'JQuery']"
     :key="text">
   <router-link tag="a">
    {{ text }}
  </router-link>
  <span>,&nbsp;</span>
</div>

The resulting output now appears as follows:

vue, react, JQuery,

However, the last comma is unnecessary. To rectify this, I utilized v-show:

<div v-for="(text, index) in ['vue', 'react', 'JQuery']"
     :key="text">
   <router-link tag="a">
    {{ text }}
  </router-link>
  <span v-show="index !== 2">,&nbsp;</span>
</div>

This solution works effectively, but I am curious if there is a simpler way to accomplish this task.

Thank you for any assistance on this matter.

Answer №1

The most effective method to take would be the one you used in your previous attempt, however, it is advisable to utilize Array.length when processing the last element to account for any changes made to the array.

<span v-show="index !== (items.length - 1)">,&nbsp;</span>

Alternatively, you can opt for pure CSS (I have included the class route on the div element):

div.route:not(:last-child) > a::after {
  content: ',';
  text-decoration: none;
}

Answer №2

Adding onto previous comments, rearranging the order can simplify avoiding unnecessary commas (by always skipping the first one, instead of worrying about array length).

<div v-for="(text, index) in ['vue', 'react', 'JQuery']"
     :key="text">
  <span v-if="index !== 0">,&nbsp;</span>
   <router-link tag="a">
    {{ text }}
  </router-link>
</div>

Answer №3

In addition to the insights shared by jom, my preference leans towards utilizing v-if rather than v-show. This is due to the guidance provided in the documentation:

It's recommended to use v-show for frequent toggling and v-if when the condition is expected to remain constant during runtime.

In this scenario, where there is no necessity to toggle the comma, it would be best not to include its rendering in the first place :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Turned off jquery on a specific div in order to resolve compatibility problems with Vue.js

Currently, I am working on a Drupal project which includes JQuery in all pages. We have recently introduced Vue.js for creating dynamic components directly in the HTML pages (not for building a single-page application). However, we are facing an issue whe ...

Using JavaScript's FOR loop in combination with AJAX

I'm encountering an issue with using AJAX and a FOR loop. Within my PHP file, there are several if statements that return different prices based on a number range (1-9). For example: 1 -> echo "15.20"; 2 -> echo "11.10"; 3 -> echo "13.65"; ...

Transforming traditional Javascript syntax into arrow function syntax

Seeking to utilize this example without relying on jquery or any other libraries. The following code is in place: let xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() {...} This code uses the old style function(). How can I conve ...

Having trouble with Angular JS $scope.$apply due to an interpolation error displaying "TypeError: Converting circular structure to JSON"?

I have created a specialized angular directive shown below: dirs.directive('sectionInfo', function(){ return { restrict: 'E', templateUrl: 'partials/section-home.html', transclude: true, co ...

Encountering a 502 Bad Gateway error when trying to deploy Nuxt.js to Google App Engine

Has anyone attempted to deploy a Nuxt app on Google App Engine? I have tried deploying from both the regular Nuxt and Express templates, but I keep encountering a 502 Bad Gateway error. I haven't made any modifications to the create-nuxt-app command. ...

Using a semicolon in the fall through of a switch case statement

When working with a fall-through in a case statement, is there any significance to including a semicolon? It seems that the fall-through functions as expected, and the semicolon may just be interpreted as an empty statement. But are there any advantages or ...

jQuery: Locate and eliminate any images in the text that appear after a specific group of tags if no images are present

Currently, I am in the process of developing a feed reader specifically designed to parse the Google News Feed. You can view and test the code on this Fiddle. My main challenge lies in removing titles and sources from the descriptions. Through my explorati ...

Issue with localStorage reducer within redux

Hello, I have written this code to start a session and I am looking to save the user's information in localStorage after they log in: 'use strict'; const defaultState ={ permission: localStorage.getItem('email') ? ...

Submitting incomplete values from a Jquery form to a MySQL database

I'm having an issue with my IntelXDK HTML5 mobile app where the form is submitting empty values to the MySQL database. Here is the HTML code for my single file app: <label class="item item-input widget uib_w_6 d-margins" data-uib="ionic/input" da ...

Transforming date format from fullCalendar dayClick event to HH:MM

I'm trying to find a way to select both start and end times when clicking on a timeslot in a day using FullCalendar. For example, if I click on the 9.00am - 9.30am slot, I want to capture both times. Here's the code snippet I have so far: $(&apo ...

Currently, I am attempting to retrieve text input through the use of AngularJS

Having trouble retrieving text input values using Angular JS? The console keeps showing undefined. <div ng-controller="favouritesController" class="col-xs-12 favList"> <input type="text" ng-model="newFav" ng-keyup= "add($event)" class="col-xs-1 ...

What is the process for incorporating PHP into a three-dimensional virtual world?

I recently completed a client's website using a combination of PHP and basic HTML/CSS. The site's main feature is the ability for users to upload images and view them in a digital art gallery. Essentially, I positioned the images against a backgr ...

What is the best way to incorporate a loading icon onto a webpage that exclusively runs JavaScript functions?

I frequently use Ajax load icons to indicate progress during ajax requests. Is there a way to achieve the same result using regular JavaScript? For instance: $('button').on('click', function(){ showLoadingIcon(); lengthyProces ...

Attempting to run a pair of JavaScript files simultaneously using the window.onload event

I'm facing an issue where two JavaScript files linked to a single HTML document are conflicting with each other. It seems like the second JS file is always taking precedence over the first one. I suspect that this might be related to both files using ...

Tips for updating the navigation bar once a user logs in

Currently, I am working on a project that involves using Laravel in conjunction with vue, and integrating JWT auth for user authentication. One of the challenges I have encountered is updating the navigation bar links based on the user's login status. ...

Shifting annotations on a Bar Graph featuring Negative Values on Google's Chart Maker

Incorporating google charts into my MVC project. Looking to create a bar chart that accommodates negative values. Desire annotations on the same side as the end of the bar for negative values (similar to positive values shown in the green box below). ht ...

Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function ...

Setting the initial viewer position in Panolens: A step-by-step guide

I've been working on setting the initial viewer position for panolens.js for a while now. Here's how the set-up looks: const panoPhoto1 = 'https://conceptcityiasi.ro/assets/images/tours/tip1/apartamente-noi-de-vanzare-iasi-dacia-1_camera-ti ...

Retrieve the current width and height of an image after the maximum width and height constraints have been applied

Check out this example The HTML: <div class="container"> <img src="http://placehold.it/500x500" alt="500x500" /> </div> <div class="container"> <img src="http://placehold.it/100x500" alt="100x500" /> </div> < ...

Can anyone explain to me why the data I'm passing as props to the React functional component is displaying as undefined?

I have encountered an issue with a pre-made React component where I am unable to see the data being passed as props when I console log it. I am unsure if I am passing the prop correctly, as I have used the same prop successfully in other class-based comp ...