Display the closing tag depending on specific conditions to simulate the behavior of a calendar

Is it possible to conditionally render a closing tag using v-if? If so, what is the correct way to do it? Initially, I tried the following:

<template v-for="day in days">
    <td class="days">{{day.number}}</td>
        <template v-if="day.isSunday">
            </tr>
            <tr>
        </template>
</template>

While this works, it does not render </tr><tr> as raw HTML - is this the expected behavior?

If conditional rendering of closing tags is not possible, what is the best way to break a table row conditionally?

In my specific scenario, I have an array of days in a month with additional information. Each day has an isSunday property, and I want to start a new row after each Sunday (simulating calendar behavior)

Answer №1

Typically, it is advised to centralize all logic in the script and utilize properties and method calls in the template section. For this particular scenario, I will establish a computed property named cptDays. Within this property, I will iterate through the days array. If a normal day is encountered, it will be added to a week. If the day is identified as Sunday, it will also be added and the week count will be incremented. The final result will be the month array that will be looped through in the template.

Important Note

I have utilized CSS styling from bootstrap to enhance the visual appearance. You have the option to remove it without affecting the functionality of your code.

new Vue({
  el: '#app',
  data: {
    days: [
      {
        "number": 1,
        "isSunday": false
      },
      {
        "number": 2,
        "isSunday": false
      },
      ...
      {
        "number": 31,
        "isSunday": false
      }
    ]
  },
  computed: {
    cptDays() {
      let month = [],
        i = 0;
      this.days.forEach((day) => {
        if (!day.isSunday) {
          if (month[i] == undefined) {
            month[i] = [];
            month[i].push(day);
          } else {
            month[i].push(day);
          }
        } else {
          month[i].push(day);
          i++;
        }
      });
      return month;
    }
  }
})
<!DOCTYPE html>
<html>
<head>
  <meta name="description" content="Vue.delete">
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.min.js"></script>
</head>
<body>
  <div id="app">
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Mon</th>
          <th>Tue</th>
          ...
          <th>Sun</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="week in cptDays">
          <td v-for="day in week ">{{day.number}}</td>
        </tr>
      </tbody>
    </table>
  </div>

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

Webpack 4 combines the power of Vue with the versatility of Typescript classes and JavaScript code simultaneously

Currently, I am in the process of migrating JS files to Typescript with the objective of being able to utilize both JS and Typescript classes within Vue. While I understand that I can convert Vue scripts into Typescript, I prefer not to do so at this momen ...

Conceal the standard style class of the p:selectOneRadio element

On my xhtml page, I've implemented p:selectOneRadio. However, I'm struggling to remove the default style class .ui-helper-hidden-accessible, resulting in the radio button icons not being visible. Here's a snippet of my code: <p:selectOne ...

A guide on effectively utilizing nested arrays within a pcolumn prime ng data table

I have a nested array structure and I am utilizing PrimeNG data table to display the data. Below is the organization of my array: this.institutionalTimetable = [ {day: "Monday", entries: [{startTime: "132", endTime: "789", recess: true, subject: 'Eng ...

The menu seems to be off-center

I'm struggling to center my menu/navigation bar horizontally. I can't seem to figure out what mistake I've made or what I've forgotten. Additionally, there is right padding after my last list item. How can I get rid of it? HTML <di ...

Tips for employing CSS hover within HTML elements?

Is there a way to achieve the following: <li style="hover:background-color:#006db9;"> I have tried this approach but it doesn't seem to work. Is there an alternative method, or do I need to include the CSS in the head section or an external CS ...

What is the best way to determine if a child div exists within a parent div?

Is there a way to determine if any div exists within the parent div? In my current scenario, I am adding two divs inside the parent div like this. $('#realTimeContents').append("<div style='width:22%; float: left; font-size:18px; line- ...

Collect data entered into the input box and store them in an array for the purpose of

I need assistance with a code that involves input boxes for users to enter numerical values, which are then stored in an array. My goal is to add these values together and display the sum using an alert when a button is clicked. However, I am struggling to ...

Transforming button alignment from vertical to horizontal in Bootstrap based on the screen size of the device

My website features a series of vertically aligned buttons on the sidebar, styled using the following CSS: CSS: .sidebar { position: fixed; left: 20px; top: 5%; width: 120px;} .sidebar .icons { font-size: 30px; margin: 21px; } ...

What yields greater performance in MongoDB: employing multiple indexes or creating multiple collections?

Currently, I am developing an application that validates users through various 3rd party services such as Facebook and Google. Each user is assigned a unique internal id (uuid v4) which corresponds to their 3rd party ids. The mongoose schema for my user do ...

Tips for creating a dynamic sidebar animation

I have recently delved into the world of web design and am eager to incorporate a sidebar into my project. While browsing through w3school, I came across a design that caught my eye, but I found myself struggling to grasp certain concepts like the 'a& ...

Error: The server selection process has encountered an unexpected issue

Embarking on my journey with MongoDB and the MERN stack, I turned to these tutorials for guidance: https://medium.com/@beaucarnes/learn-the-mern-stack-by-building-an-exercise-tracker-mern-tutorial-59c13c1237a1 https://www.youtube.com/watch?v=7CqJlxBYj-M ...

Dynamic data binding in AngularJS with dynamically generated views

The scenario: Currently, I am constructing a wizard in AngularJS that contains tabbed content with each tab representing a step in the wizard. These steps are fetched from the database through a Laravel controller and displayed using ng-repeat. Each tab c ...

What is the correct way to remove listeners in componentWillUnmount using React, and why is binding necessary in the constructor?

I'm feeling a bit perplexed, can someone explain the distinction between these two snippets of code: constructor(props) { super(props); this.state = { openPane: false } this.togglePaneHelper = this.togglePaneHelper.bind(this); ...

Tips for transferring the ID from one element to another using JavaScript

I'm attempting to create a slideshow using icons all within one class. The "active" style class will have an ID and represent the current picture. By clicking either the left or right button, I aim to change the style of the active class. const l ...

Is the Packery image grid only functional when the background image is specified in CSS and not in JavaScript? Perhaps we need to look into using Await/Sem

I've successfully implemented a packery image grid that is responsive and functional when the background image in the .item-content section is defined in the CSS file: http://codepen.io/anon/pen/eJdapq .item-content { width: 100%; height: 100%; ...

Preventing an iframe from reloading when transferring it to a new parent using appendChild

I'm looking to relocate an iframe to a different parent element while maintaining the iframe's current state (including scroll position and any entered form data). Unfortunately, when I use appendChild() to move the iframe, it reloads and resets ...

How can you determine the status of an individual checkbox within a reactjs (material-table) component?

In my project, I have implemented a table that displays a list of students retrieved from a database. Upon clicking on each student row, a modal popup appears showing another table with 4 rows and 3 columns. Each column in the modal contains 4 checkboxes. ...

What is the reason for the lack of invocation of the next-auth jwt callback during page transitions?

Utilizing the next-auth Credentials provider, I have set up authentication in my Next.js application with a custom Django backend. Below is my jwt callback function: async jwt(token, user, account) { if (user && account) { // The user ha ...

Preserve the values of checkboxes throughout the entire website by utilizing localStorage

Example A functionality in the example allows users to add images to a container by clicking on checkboxes. However, there is an issue where when a checkbox is checked on one page to store an image, and then another checkbox is checked on a different page ...

Validating HTML forms using Javascript without displaying innerHTML feedback

Hey, I'm just diving into web development and I'm struggling to figure out why my innerHTML content isn't displaying on the page. Can anyone offer some assistance? I'm trying to display error messages if certain fields are left empty, b ...