What is the best way to narrow down the results of a v-for loop in VueJS using a computed property?

I've been attempting to utilize a computed property to filter the displayed results while using a v-for loop. However, despite setting the bars.js data to only show one item with 'true', all bars are still visible in my application. I expected to see only one bar but seems like something is going wrong. Any assistance would be greatly appreciated.

My reference source is https://medium.com/devmarketer/how-to-add-conditional-statements-to-v-for-loops-in-vue-js-c0b4d17e7dfd

<li v-for="bar in bars" :key="bar.id">
    <h2>{{ bar.barName }}</h2>
</li>

<script>
import bars from "./../data/bars";
export default {
  data() {
    return {
      bars: bars
    };
  },
  computed: {
      bars: function() {
        return this.default.filter(function(u) {
          return u.newListing
      })
    }
  }
};
</script>

In a separate file named bars.js, the contents include:

export default [
    {
        barName: "Mikes",
        newListing: true,
    },
    {
        barName: "Cheers",
        newListing: false,
    },
    {
        barName: "Biker Bar",
        newListing: false,
    }
];

Answer №1

Your code contains two instances of the bars variable, making it unclear which one the template should utilize. It appears to be selecting the bars from the data. To resolve this issue, consider renaming the computed property to something distinct and then referencing it in the template. For instance:

export default {
    data() {
      return {
        bars:  [/* your bar data goes here */]
      };
    },
    computed: {
        bars_filtered: function() {
          return this.bars.filter(u => u.newListing)
      }
    }
  };

In the template, you would iterate over bars_filtered:

v-for="bar in bars_filtered"

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 type-safe alternative to the setTimeout function that I can use?

When running my tests, I encountered an issue with the setTimeout method making them run slower than desired. I initially attempted to address this by using "any" in my code... but that led to complaints from eslint and others. Now, I have implemented a ...

I am currently utilizing react-admin, however, I am encountering an issue with the heavy build causing errors

Currently, I am working on developing the frontend using react-admin. Initially, I intended to utilize NextJS and found a helpful reference article. Reference: When attempting to run next dev, everything worked smoothly without any errors. However, when ...

Using a function from one class within another class by passing it as a prop

Below are the methods found in my Search.tsx class. renderSuggestion(suggestion) { <div className="buttons"> <button className="button">View Location</button> <button className="button whitebutton" onClick={this.h ...

Integrating array elements into the keys and values of an object

Given the array below: const Array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'] How can I transform it into an object like this? const Object = { Michael: student, John: cop, Juli ...

Accessing the return value from an ASP.NET web service in JavaScript outside of the callback function

I am facing an issue with my ASP.NET web service that returns a simple string value. I have successfully called this web service using JavaScript and the script manager. However, I am in need of accessing the return value directly from where I made the cal ...

Is it possible to reference the prior value of a computed Angular signal in any way?

Is it possible to dynamically add new values from signal A to the existing values in signal B, similar to how the scan operator works in RxJS? I am looking for something along the lines of signalB = computed((value) => [...value, signalA()]). Any sugg ...

Version 13 of the Discord slash command encounters an "interaction failed" error

After implementing the slash commands in Discord v13 as per the instructions on discordjs.guide, I encountered an issue when trying to use the commands - interaction failed. Here is a snippet of my code: // Here goes the code const { Client, Collection, ...

The jQuery Multiselect filter contradicts the functionality of single select feature

http://jsfiddle.net/rH2K6/ <-- The Single Select feature is functioning correctly in this example. $("select").multiselect({ multiple: false, click: function(event, ui){ } http://jsfiddle.net/d3CLM/ <-- The Single Select breaks down in this sc ...

Using three.js to establish an Image for Particle

I am looking to make some changes to this demo: Instead of having colored particles, I want to assign an image to each one. Should I use a cube for this purpose? Or is there a way to use an image with Vector3? Here is the code for the example: i ...

The art of perfect alignment: Mastering the positioning of Material-UI Grid

This issue has been resolved Hey there, I'm currently working on a React App with Material-UI and I'm trying to center a Grid item that includes a Card along with two additional Grid items. Below is the relevant code snippet. Although the Cards ...

A function that handles HTTP request and response

In order to decrypt data, I need to retrieve the encrypted response by hitting a specific URL and then use that encrypted data along with a key to decrypt it. Initially, I attempted to fetch the data response using POSTMAN, but all I got back was a series ...

Array filtering using one array condition and additional boolean conditions

Sorting through the carArray based on user-specified conditions. If a user selects the red checkbox, only cars with red paint will be displayed. If a user selects the green checkbox, only cars with green paint will be displayed. If both the red and green ...

Is there a way to iterate through indexed variables in javascript?

After receiving an array of data from a JQuery .ajax function, I noticed that the fields in the array are named and numbered like part1, part2, part3, etc. I attempted to loop through this data using the code below, but unfortunately, it resulted in NaN: ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

Is it possible to import a class from a different project or module in TypeScript?

I am attempting to modify the build task in Typescript within this specific project: https://github.com/Microsoft/app-store-vsts-extension/blob/master/Tasks/app-store-promote/app-store-promote.ts I am looking to incorporate an import similar to the one be ...

When I attempt to click on the Cancel button, the database row remains undeleted

After a user clicks on the "Cancel" button, I want to reset the source and remove the iframe to prevent the file from being uploaded to the server. This function is currently working as intended. However, I am facing an issue where even after clicking on ...

HTML5 for advanced positioning and layering of multiple canvases

I have 2 canvas layers stacked atop each other, but I need to position them relative to the entire page. The dimensions of both layers are fixed at a width of 800 and a height of 300. My goal is to center the canvas layers regardless of screen size, with ...

Testing the equality of nested arrays: A step-by-step guide

My maze generator creates walls for each "cell", resulting in duplicate walls - such as the left wall of one cell being identical to the right wall of the adjacent cell. I have managed to convert the maze data into a different program where it is stored in ...

My initial experience with vue.js has been complicated by issues with routers

I've recently dipped my toes into the world of Javascript and vue.js. After following a tutorial on creating a single page shopping application, I decided to incorporate routers into my learning project. However, I encountered some interesting error ...

Leverage cookies within a custom service in AngularJS

I attempted to implement angular cookies within a custom service, only to encounter the following error: Unknown provider: ngCookiesProvider <- ngCookies <- checkLoginService My approach involves storing modules, controllers, and services in separat ...