Difficulty arising from implementing v-if as a filter within a v-for loop in Vue.js

I'm struggling a bit with setting up a conditional statement using v-if along with a loop using v-for in Vue. Here's what I have so far:

<div class="row form-group" v-for="(article, key, index) in articles" :key="key" v-if="article.pubdate(first four characters)">={{ filterYear}} >

I'm unsure of how to extract the first four characters from the pubdate and treat it as a number, as well as how to pass in the filterYear. The data structure for articles is JSON returned via Axios. However, the format of pubdate is: year, space, then month (e.g., 2007 Aug or 2009 Aug 1).

My goal is to isolate a year and use it within the v-if, displaying only articles written during or after that specific year. I also have similar functionality on the JavaScript side where values are identified and converted into a string (uid_string). Check out this example on CodePen.

Answer №1

One way to simplify the loop filter instead of using a v-if condition is by utilizing a computed property. This method not only streamlines the template for the loop but also eliminates the need for extra calculations to determine the ordinal number for each item, as the index of the array can naturally serve as the ordinal number.

For instance, you can integrate the suggested filter from @Stephen into a computed property:

<script>
export default {
  computed: {
    filteredArticles() {
      const { articles, filterYear } = this
      return Object.values(articles)
        .filter(article => parseInt(article.pubdate.substring(0,4)) >= filterYear)
    }
  }
}
</script>

After defining the computed property, simply utilize it in your template like so:

<template>
  <div v-for="(article, index) in filteredArticles" :key="article.uid">
   ...
  </div>
</template>

To see a demonstration of this approach, check out this demo.

Answer №2

If you want to extract an integer year from the first four characters:

parseInt(article.pubdate.substring(0, 4))
<div  
v-for="(article, key, index) in articles" 
:key="key" 
v-if="parseInt(article.pubdate.substring(0, 4))>=filterYear">

Your code goes here... 
To display the article JSON, use curly braces: {{article}}.
Similarly for the date {{article.date}}, etc.
Avoid using curly braces within template attributes.

</div>

An advantage of Vue is that all template properties are relative to the component, eliminating the need to use this. as a reference.

To tidy up the template, consider moving the parseInt(...) and comparison logic to a component method.

You can see these changes in action on your updated codepen: https://codepen.io/anon/pen/NVrvre?editors=1111

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

Spacing in a vertical orientation with Vuetify

Feeling like it's 11/10 chance that it's just too late in the day and my brain is in idiot mode, but let's give it a shot... So, I have a list of navigation links (v-list-item in a v-list) ... I'm attempting to make one of the links s ...

Press the button to automatically scroll to a designated div section

One of the challenges I'm facing involves a fixed menu and content box (div) on a webpage. Whenever I click on the menu, the content box should scroll to a specific div. Initially, everything was working fine. Here is a sample of it in action: http ...

Issue when trying to use both the name and value attributes in an input field simultaneously

When the attribute "name" is omitted, the value specified in "value" displays correctly. However, when I include the required "name" attribute to work with [(ngModel)], the "value" attribute stops functioning. Without using the "name" attribute, an error ...

Ways to assign a value to an input element in AngularJS without impacting its ngModel

JAVASCRIPT: .directive('search', [function () { return { restrict: 'A', link: function (scope, element, attrs) { attrs.$set('placeholder', 'Word...'); console.log(attrs); ...

Developing an object that displays animated effects when modifying its properties, such as visibility, and more

Exploring the realm of animations in JavaScript and AngularJS has led me to the idea of creating a unique JavaScript object. Imagine having the ability to define an object where setting an attribute like obj.visible = true Would automatically make the ...

Is there a way to prevent tags from wrapping and showcase them all in a single line when utilizing the jQuery select2 plugin?

I have a requirement to prevent tags from wrapping and instead display them in a single line using the jQuery TagIt plugin. Check out my preview: https://i.stack.imgur.com/lYhsi.png My goal is to have all the tags displayed on a single line without wra ...

Understanding the behavior of the enter key in Angular and Material forms

When creating forms in my MEAN application, I include the following code: <form novalidate [formGroup]="thesisForm" enctype="multipart/form-data" (keydown.enter)="$event.preventDefault()" (keydown.shift.enter)="$ev ...

WebSocket connection established on port 8888, while the web server is running on port 80 - incompatible to merge the two services

Here is some node.js server-side code that involves watching a file and sending modifications to the browser: var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') a ...

Having trouble running Javascript with jQuery's ajax load()?

I have encountered this problem and despite reading multiple posts, I am unable to find a solution. My challenge lies in loading an HTML file into a div that contains an unordered list. The list is supposed to function as an expanded menu with sub-items, ...

Notifying with Jquery Alert after looping through routes using foreach loop

I am trying to create a jQuery alert message that displays after clicking on a dynamically generated button in the view using a foreach loop. The issue I am facing is that only the first button in the loop triggers the alert, while the subsequent buttons ...

Trouble with Loading Google Place Autocomplete API in HTML

I utilized the Google MAP Place Autocomplete API for a web project. Click here to view the code and output. <form> <input id="origin-input" type="text" class="form-control" placeholder="From"/> <br/> <input id="de ...

Trouble with Bootstrap Popover's visibility

My current setup involves a popover that is not initializing properly. The code I am using is shown below: HTML: <div data-toggle="popover" data-placement="bottom" data-content="xyz">...</div> JavaScript: $(function () { $('[data-t ...

What is the best way to showcase page content once the page has finished loading?

I'm facing an issue with my website. It has a large amount of content that I need to display in a jQuery table. The problem is that while the page is loading, all rows of the table are showing up and making the page extremely long instead of being sho ...

Detect click outside in JavaScript for closing

While this topic has been discussed before, each issue presents its own unique challenges. Despite trying various solutions and examples for making the submenu close when clicking outside of it, I have not had any success. Is there a way to make the uslug ...

When attempting to modify an element in an array within a state-managed object, the input field loses focus

In attempting to address my issue, I have crafted what I believe to be the most concise code example. The main goal is to display a table on the page populated with exercise data retrieved from a database. This data is then assigned to an array of objects ...

What is the process for installing vue-cli?

I'm currently diving into the world of Node Package Manager and Vue, trying to wrap my head around the Vue CLI. On the vue.js website, they provide instructions for running the official Vue CLI: https://i.stack.imgur.com/0OCrc.png I have a few inqu ...

AJAX function in Chrome console is throwing an error message stating "Unexpected Token }"

Dealing with this issue has been quite unusual for me. I've spent the last 3 days trying to troubleshoot it, but now it's no longer bothering me. The situation involves a button and a textbox that sends the data from the textbox to a PHP page whe ...

In Next.js, encountering an error when using canvas drawImage

I am attempting to upload a local image onto a canvas element, but I keep encountering an error: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLCanvasElement ...

The function req.send('null') does not exist in the Node.js MySQL library

I am struggling with inserting a form into a MySql database. The values are stored in the database from the form, but the table displayed on the page does not refresh. I can only see the entries when I restart the server and revisit the page. Furthermore, ...

Error encountered in vue.js due to a ReferenceError when the resize event is used

I'm having trouble obtaining the window height when resizing, and I keep encountering the error ReferenceError: calcOfSliderHeight is not defined. Can someone explain what's happening? Here is my code: let example = new Vue({ el: '#exam ...