Tips for acquiring an object to utilize in v-bind within a v-for loop

Consider this code snippet:

<ol class="breadcrumb arr-right">
    <li v-for="(url,name, index) in links" v-bind:class=" (index == (links.length -1)) ? 'breadcrumb-item active' : 'breadcrumb-item'">
        <a v-bind:href="url">{{ name }}</a>
    </li>
</ol>

The issue at hand is that links.length is always undefined. While everything else in the code works fine, the ternary operation faces a problem due to the undefined state of links. Can you suggest a way to correctly access links from within the v-bind code?

Answer №1

Given that links is classified as an object, it is important to note that links.length will consistently return undefined due to the fact that an object does not possess a length property, unlike an Array which does.

Determining the size of the object can be achieved by identifying the length of its keys. It is worth mentioning that Object.keys() generates an Array containing the keys of the object, enabling the utilization of Array.prototype.length on the outcome to ascertain the size of the object.

const class = index === Object.keys(links).length - 1
            ? 'breadcrumb-item active'
            : 'breadcrumb-item'

The structure for your class binding appears to be slightly inaccurate. One approach is to merge object syntax with array syntax as illustrated below:

<li v-bind:class="[ { 'active': index === Object.keys(links).length - 1 }, 'breadcrumb-item' ]">

demo 1

Alternatively, you can opt for object syntax only:

<li class="breadcrumb-item" v-bind:class="{ 'active': index === Object.keys(links).length - 1 }">

demo 2

In scenarios where your goal involves styling the final <li> element, there might be a simpler CSS solution. Instead of applying .breadcrumb-item.active to the last item, consider utilizing :last-of-type:

.breadcrumb-item:last-of-type {
  /* your styles here */
}

demo 3

Answer №2

Give this a try:

<ol class="breadcrumb arr-right">
    <li v-for="(item, index) in links" v-bind:class=" (index == (links.length -1)) ? 'breadcrumb-item active' : 'breadcrumb-item'">
        <a v-bind:href="item.url">{{ item.name }}</a>
    </li>
</ol>

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

Is there a way to keep the node text in place and prevent overlapping in my D3.js tree?

I'm facing an issue with long text strings in my D3 tree. The nodes move according to the tree structure, but how can I handle excessively long node-text? For instance, if the label "T-ALL" had a longer name, it could overlap with the neighboring nod ...

Restrict the selection of dates in the jQuery UI datepicker by disabling public holidays, weekends, the next day after 10am, and only allowing Tuesday, Wednesday, and Thursday as

I found a code snippet on disabling weekends, public holidays, and the next day after 10 am using JQuery UI Datepicker. However, I'm facing an issue where I want to restrict selections to only Tuesday, Wednesday, and Thursday. // JavaScript logic for ...

Show specific content based on which button is selected in HTML

I am working on a project where I have three buttons in HTML - orders, products, and supplier. The goal is to display different content based on which button the user clicks: orders, products, or supplier information. function showData(parameter){ i ...

Can you provide me with some insight on the process of iterating through an object utilizing the

I've developed an app that randomly plays a sound from a selected array when a button is pressed. Now, I want to add the functionality to display and play all sounds in the array upon request. I've explored various methods such as for loops and ...

A superior method for implementing CSS keyframe transitions

Currently, I am utilizing the Rico St.Cruz brilliant query.transit library for my work. However, I need to make some changes involving classes instead of CSS transitions. Although I am not very confident in CSS transitions, I attempted to replace: JS: $ ...

Dealing with encoding problems in Node.JS when parsing JSON data with UTF-

I have developed a small script that allows me to fetch keyword suggestions from the Google search API. One major issue I am facing is when the response contains special characters (such as à é ù etc.): my application returns unreadable keywords like: ...

What is the best way to retrieve the parent div's ID with JavaScript and Selenium?

My current project involves utilizing webdriverjs, and I am faced with the challenge of retrieving the parent id of a specific webelement among multiple elements with similar classes. Each element has a different id that gets dynamically generated when a m ...

Managing traffic in Google Kubernetes Engine (GKE)

I am encountering an issue with our website deployment on GKE, which consists of 10 pods. When deploying a new version, we use MAXsurge=1 and MAXunavailable=0. Upon trying to access the website during a new deployment, I sometimes only see the header in t ...

Automatically close the popup each time it is displayed (using jQuery/JavaScript)

I am having issues with auto-closing my popup each time I open it. The current code I have only closes the popup the first time, requiring me to refresh the browser in order to auto-close it again. Can someone please assist me in writing a new code that ...

Having trouble displaying the image on the screen with Material UI and React while using Higher Order Components (HOC) for

I'm facing an issue with displaying an image on my Material UI Card. Despite checking the directory and ensuring it's correct, the image still doesn't show up. Additionally, I need assistance in modularizing my code to avoid repetition. I at ...

Using express.static can cause an issue with a Nodejitsu application

I'm completely puzzled by this issue that keeps cropping up. Whenever I try to add a static path to my app, I encounter an error on the hosting platform I use called "nodejitsu". The error message indicates that the application is not functioning prop ...

The error message "TypeError: Unable to access property of undefined when using web sockets"

Exploring Isomorphic framework for React and integrating Pusher for websockets communication. I'm encountering difficulty accessing the state within the componentDidMount() function. class TopbarNotification extends Component { state = { vis ...

IE8 is not properly handling nested HTML elements that have the display:none property set

I am currently using jQuery to create a smooth fade-in effect for an <article> element that contains a <section> element. The outer element has CSS properties of display:none, position:fixed, and z-index:5. Meanwhile, the inner element is styl ...

What are the steps for retrieving a JSON object within an array?

var jsonData = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue" :{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text" :"Size32","price":"22","isSelec ...

serverless with Node.js and AWS encountering a 'TypeError' with the message 'callback is not a function'

Within my handler.js file, I am utilizing the getQuotation() function from the lalamove/index.js file by passing the string "hi" as an argument. 'use strict'; var lalamove = require('./lalamove/index.js'); module.exports.getEstimate = ...

Using Vue Firestore to assign a boolean value

Recently delved into the world of Firebase and keen on exploring Firestore integration with Vue.js. Starting off simple, I've created a collection called 'Presenter' with a document titled 'controls' that stores a single value &apo ...

Discovering instructions on locating Material UI component documentation

I'm having trouble locating proper documentation for MUI components. Whenever I attempt to replicate an example from the site, I struggle to customize it to fit my requirements. There are numerous props used in these examples that I can't seem to ...

Passing the value of the selected calendar date to the controller

How can I pass the value generated by this calendar_date_select to the controller? Any suggestions on how to modify the onchange code? <%= calendar_date_select_tag "meeting_date_1", @time, :embedded => true, :time => true, :minut ...

Creating trails by following the cursor's movement in KineticJS

Currently, I am working on a drawing application using KineticJS. While I have successfully used it to draw shapes and straight lines by following the method outlined in KineticJS - Drawing Lines with Mouse, I now need to draw a line along the mouse's ...

Gamepad interference causing obstruction of `requestAnimationFrame()`

I'm currently working with the Gamepad API and finding it a bit challenging due to its limited development. It appears that there is no "gamepadbuttondown" event available, which can be frustrating. I came across a library called 'awesome-react-g ...