Tips for excluding a value in a Vue loop

Is there a way to exclude the value "Three" from the loop in the following code snippet?

<script >
  const routes = [
    {name: 'One', value: 24},
    {name: 'Two', value: 25},
    {name: 'Three', value: 26},
    {name: 'Four', value: 34},
  ]
  export default {
    name: 'App',
    computed: {
      routes(){
        return routes;
      }
    },
  } 
</script>

<template>  
  <div id="app">
    <div class="movies">
      <h2>Which movie?</h2>      
      <ul>
        <li v-for="(route in routes" >
          <span v-if="route.name !== 'Three'">{{ route.name }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<style scoped>

</style>

The displayed output of the above code is like this:

https://i.sstatic.net/GClp6.png

An empty "li" tag is added when the condition is not met.

If I modify the structure by placing the v-if within the v-for as shown below:

<template>  
  <div id="app">
    <div class="movies">
      <h2>Which movie?</h2>      
      <ul>
        <li v-for="(route in routes" v-if="route.name !== 'Three'">
          <span>{{ route.name }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

I encounter an error message like:

https://i.sstatic.net/WIn3e.png

Any suggestions on how to resolve this issue would be greatly appreciated!

Answer №1

Attempt to eliminate the number 3 from a calculated property:

const cars = [
  {brand: 'Honda', price: 20000},
  {brand: 'Toyota', price: 25000},
  {brand: 'Ford', price: 30000},
  {brand: 'Chevrolet', price: 35000},
]
new Vue({
  el: "#vehicles",
  computed: {
    filteredCars(){
      return cars.filter(c => c.brand !== "Ford");
    }
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vehicles">
  <div class="cars">
    <h2>Which car?</h2>      
    <ul>
      <li v-for="car in filteredCars" >
        <span>{{ car.brand }}</span>
      </li>
    </ul>
  </div>
</div>

Answer №2

Ever thought about only displaying certain routes in your v-for loop?

<li v-for="route in routes.filter(r => r.name !== 'Three')" >

Another option is to create a computed property to handle this.

Answer №3

Marco's reference in a comment led me to uncover valuable information at https://vuejs.org/guide/essentials/list.html#v-for-with-v-if. Drawing from this, I crafted the following solution:

<template>  
  <div id="app">
    <div class="movies">
      <h2>Which movie?</h2>      
      <ul>
        <template v-for="route in routes">
          <li v-if="route.name !== 'Four'">
            <span>{{ route.name }}</span>
          </li>  
        </template>        
      </ul>
    </div>
  </div>
</template>

This setup resembles Vue syntax and eliminates errors caused by v-if taking precedence over v-for.

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

Different ways to enhance max-http-header-size in Vue application

After being redirected from another application, I am unable to open the page and receive an error in the console: Failed to load resource: the server responded with a status of 431 (Request Header Fields Too Large). I came across information about max-h ...

What are the best practices for managing live notifications with WebSocket technology?

I have developed a real-time chat application in React.js with Socket.io, but I want to implement a new feature. Currently, User A and User B can only communicate if they both have the chat open. I would like to notify User B with a popup/notification wh ...

Using NodeJS to convert a Base64 string into a JPEG image with the help of either NodeJS or

I have successfully stored a JPEG image in my MySQL database using the longblob format. Now, when I retrieve the longblob data, I am only getting a base64 string. How can I convert this base64 string back to a readable JPEG image using MySQL or Node.js? B ...

What is the best way to create a line break within a loop in React?

I have a react component that I need to format into multiple lines, specifically having 2 boxes on top and 3 below in a looped return. The desired layout is to stack the boxes in 2x2 or 2x3 depending on the total number of boxes generated by the loop. So, ...

I'm struggling to figure out where I went wrong with the Mongoose unique pre-save validation. What could

I am in the process of developing a User model that requires a unique username. Below is the code snippet for the model: var mongoose = require("mongoose"); var Schema = mongoose.Schema; var UserSchema = new Schema({ username: String, password: ...

JavaScript creates dynamic three.js animations on top of an image

When you visit the link above, you will see an animation of stars and a sphere reflecting that animation. My goal is to have https://i.sstatic.net/VpxWH.png It would mean that the reflective sphere is displayed on the astronaut's helmet. I am strug ...

As the background image shifts, it gradually grows in size

I'm attempting to create an interesting visual effect where a background image moves horizontally and loops seamlessly, creating the illusion of an infinite loop of images. Using only HTML and CSS, I've run into an issue where the background ima ...

What is the best method for assigning a default value to the file input tag in HTML?

Can anyone help me with this code snippet? <input name="GG" type="file" value="< ?php echo $data['image'] ?>"> I was trying to set a default value in the form edit, but it seems to not be working. Does anyone know how to set a defau ...

Exploring the process of building a JavaScript function inside a JSON object using Gson

Can Gson generate JSON that includes a JavaScript function without a key nested within? { autosave: { save( editor ) { return editor.saveData( editor.id, editor.getData() ); }, waitingTime: 2000 } Appreciate any hel ...

Why won't the $emit from custom filter reach the callback in vue-tables-2?

I'm facing a challenge with implementing a custom filter in vue-tables-2 that should emit an event from a nested, single-page component in Vue. It seems like the issue might be related to not handling it correctly in the parent components. Inside the ...

Registering components globally in Vue using the <script> tag allows for seamless integration

I'm currently diving into Vue and am interested in incorporating vue-tabs into my project. The guidelines for globally "installing" it are as follows: //in your app.js or a similar file // import Vue from 'vue'; // Already available imp ...

Tips for managing test cases to execute on various browsers using protractor

unique challenge observing the unique challenge image provided, there are two browsers executing different test scenarios. I aim to execute spec 7 on both active browsers (browser1 and browser2) with an interactive approach like a chat application. After ...

Continuously inserting new records to a JSON file using a while loop

Is there a way to continuously add key value pairs to a JSON object within a while loop? var sName = "string_"; var aKeys = ["1", "2", "3"]; var sKey = "key"; var n = 1; var aObj = {}; var l = aKeys.length; for(let i=0; i < l; i++){ while(n < 5) ...

Displaying a single result in Angular from JSON without using the ng-repeat filter

Currently, I am working on developing an app to display news updates from a JSON API. The issue I am facing is that loading all the data from the JSON and filtering it using ng-repeat is causing slow performance, as there is a large amount of data. I woul ...

What is the best way to increase the quantity of items in an array while simultaneously reducing the values of one or more specified keys for each object?

I have the following array: const disabledDays = [ { year: selectedDay.year, month: selectedDay.month, day: selectedDay.day -1 } ]; and I intend to pass it as a prop to a component: <DatePicker v ...

Remain on the React page following an HTTP POST request to Flask

Is there a way to stay on the React frontend (localhost 3000) after completing a POST request to a Flask backend from a React form, without redirecting in the Flask backend? Relevant code: export const DateForm = () => { return ( <div&g ...

Arrange the array in chronological order based on the month and year

I'm looking for assistance with sorting an array by month and year to display on a chart in the correct order. Array1: ['Mar19','Apr18','Jun18','Jul18','May18','Jan19'....]; Desired Output: ...

Node.js is receiving an empty body from Postman when using form-data in the request

Even though I've searched extensively, I still have not found a solution to my specific issue despite it being asked before. const express = require("express"); require("dotenv").config({ path: ".env", }); const PORT = ...

How do you effectively manage components within the Vue framework?

I'm just starting out with vue and I'm still learning how to organize things effectively. Currently, I am working on my own small project using Vue, which is a booklist app. It's similar to a basic todo app but includes additional features ...

Is it advisable to start a function within the componentDidMount() method in ReactJS when using promises?

I am developing an application that utilizes promises to manage animations. After a few attempts, I encountered the following error message: Warning: Can’t call setState on a component that is not yet mounted. This is a no-op, but it might indica ...