Dynamic Array Rendering with Vue.js Computed Properties

As a newcomer to Vue, I've dedicated the last few hours to learning how to implement conditional logic in methods and computed properties for a practice birthday component project. While exploring different approaches, I noticed some developers utilizing if/else statements within their computed properties. However, I encountered an error message stating

Unexpected side effect in "displayDays" computed property
.

My goal is to construct a component that outputs a Date of Birth (DOB) string in the format mm/dd/yyyy when selecting each individual element of the DOB through a list of options (in this case, buttons). Upon clicking on the birthday month, the corresponding list of days for that month should be displayed in the template.

That's where I hit a roadblock. Initially, I attempted to populate the days array in the method click event selectedMonth(). After some investigation, I learned that I needed to use computed properties to dynamically alter the data within the days array as desired. Despite multiple unsuccessful attempts to implement an error-free if/else statement within the computed section, I'm unsure of what I may be overlooking.

Any assistance or guidance on this matter would be greatly valued!

Below is the provided code:

<template>
  <div>
    (...)
  </div>
</template>

<script>
  export default {
    name: 'birthday',
    data() {
      (...)
    },
    methods: {
      selectedMonth(month) {
        (...)
      },
      selectedDay(day) {
        (...)
      },
      submittedYear(year) {
        (...)
      }
    },
    computed: {
      displayDays() {
        (...)
      }
    }
  }
</script>

<style scoped>
(...)
</style>

Answer №1

The problem lies within the computed property section.

Simply assigning this.days with the required array inside the displayDays computed method is not the correct approach. Instead, you should return the required array from the computed property.

Furthermore, computed properties will be re-evaluated whenever any of the parameters inside the computed property changes. In this case, you are using this.month inside the computed property, but there is no update for this anywhere in your code. As a result, your computed property will never be re-evaluated. To rectify this, assign the value for this.month inside the selectedMonth method as this.month = month.text;. When the value of this.month changes, your computed property will be re-evaluated with the new value for this.month.

Working Code Example

 const example = {
    name: 'example',
    initialize() {
        this.data = {
            values: [1, 2, 3, 4, 5],
            selected: null,
            query: ''
        };
    },
    updateQuery(query) {
        this.data.query = query;
    },
    getFilteredValues() {
        return this.data.values.filter(value => value > this.data.query);
    }
}
#values, #selected, #query {
    border: 1px solid #ccc;
}

#values div, #selected div, #query {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    gap: 5px;
    justify-content: center;
    padding: 10px;
}

button {
    text-align: center;
    width: 100px;
    height: 40px;
    background: #fff;
    border-radius: 25px;
    border: 1px solid #5500B3;
    line-height: 36px;
}

#values div {
    justify-content: left;
}

#values div button {
    border-radius: 10px;
    width: 40px;
}

#values div button:hover {
    cursor: pointer;
    background: #f0f0f0;
}

#query input {
    font-size: 18px;
    font-weight: bold;
    border: 1px solid #ececec;
    padding: 8px 14px;
    background: #ececec;
    border-radius: 12px;
    height: 50px;
}

.uppercase {
    text-transform: uppercase;
}
<script src="https://example.com/vue.js"></script>
<div id="example">
    <div id="values">
        <label class="uppercase">Values</label>
        <label>Select an item</label>
        <div>
            <button class="value">1</button>
            <button class="value">2</button>
            <button class="value">3</button>
            <button class="value">4</button>
            <button class="value">5</button>
        </div>
    </div>

    <div id="selected">
        <label class="uppercase">Selected</label>
        <label>Selected item</label>
        <div>
            <button class="selected"></button>
        </div>
    </div>

    <div id="query">
        <label class="uppercase">Query</label>
        <label>Enter query</label>
        <input type="text" id="inputQuery" name="query">
    </div>

    <button>
        Submit
    </button>

</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

Trouble with passing a nodejs variable into a nested function

I've been working on the code below but I'm having trouble getting the inner function .each to successfully call res.write with the results from the MongoDB query. At first, I thought the issue might be related to the variable res not being glob ...

The array is devoid of any elements, despite having been efficiently mapped

I'm facing some challenges with the _.map function from underscore.js library (http://underscorejs.org). getCalories: function() { var encode = "1%20"; var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#"; _.m ...

What are some ways to implement pagination on a website?

Struggling to implement pagination without Laravel? You're not alone. The challenge lies in creating a cycle that displays the correct number of pages, with each page containing 10 posts out of a total of 98. While you've managed to calculate the ...

Localized Error: The property 'clientWidth' cannot be retrieved as the object is null or undefined

The issue with the error message seems to only occur on Internet Explorer, and unfortunately there doesn't seem to be a clear solution at the moment. Even after setting http-equiv="X-UA-Compatible" to IE8, the problem persists and I cannot seem to re ...

Vue: The function "priceFilter" is not defined in this context

function sanitizeInput(event) { event.target.value = event.target.value.replace(/[^\d.]/g, ""); event.target.value = event.target.value.replace(/^\./g, ""); event.target.value = event.target.value.replace(/\.{2,}/g, "."); event.targe ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

Attempt to efficiently register components automatically on a global scale in Vue by utilizing the powerful combination of Laravel-Mix and Webpack

In my previous projects with Vue, which were based in a Laravel-Mix/Webpack runtime environment, I used to individually register components and views as needed. This was done by importing them and extending Vue: import BaseButton from './components/Ba ...

React - Obtain User Login Details and Verify

I am working on a React project that includes a Login Form. The code has been organized into small components for reusability, but I am unsure of how to retrieve and validate user credentials (username and password). Is there a method available to validate ...

Comparison of Chrome's compatibility with Bootstrap and Edge

Firefox Safari I am facing an issue that seems obvious, but I am unable to pinpoint the exact cause. It just doesn't seem right for no apparent reason. is the website in question. I have tried various troubleshooting methods such as inspecting th ...

What steps can I take to reset my JavaScript code once its original purpose has been fulfilled?

I created this code, learning as I went along. It measures Beats Per Minute as one clicks the left-mouse-button each time they feel a pulse. After 10 clicks, the JavaScript code takes all the values in the array and calculates an average BPM. The issue ar ...

Applying the Active CSS class to a Bootstrap Carousel

I'm currently working with a bootstrap carousel that displays dynamic images fetched from a backend API. The challenge I'm facing is that I'm unable to set the active class for the individual slides. If I hardcode the active class, all slide ...

"Encountering a 403 error while using the request method in Node.js

app.post("/",function(req,res){ // console.log(req.body.crypto); request("https://apiv2.bitcoinaverage.com/indices/global/ticker/all?crypto=BTC&fiat=USD,EUR",function(error,response,body){ console.error('error:', error ...

"I'm curious about how to reset a form in reactjs hooks after it has been submitted

Just dipped my toes into the world of hooks and I'm stumped on how to clear input fields post-submit. Tried form.reset() but it's not doing the trick. import { useForm } from "react-hook-form"; import.... export default function AddUse ...

Interactive Timekeeping Tool with AngularJS Alarm Feature

I have successfully implemented the functionality to display the system time and date. Additionally, I have set up textboxes for users to input the time they want to set as their first alarm. My current goal is to trigger a particular action once the syst ...

Unable to choose fields and options within the popup box

Interacting with jQuery: $("#type_name").click(function(){ $("body").append('<div class="modalOverlay">'); $("#add_form").fadeIn(1000); $("#first_name").val(""); $("#email").val(""); ...

Javascript Code Tweaking... Is it Just a Minor Oversight?

I've been working on incorporating a jQuery Exit LightBox into my website and came across this straightforward tutorial - The concept of the pop-up is quite clever, but I've run into an issue where it only functions properly when a visitor is at ...

Limit access to route in ExpressJS only to internal redirects

I'm managing an ExpressJS application that includes specific routes which I intend to only function when redirected to from my code, rather than input directly into the URL. Essentially, if a user attempts to enter "myapp.com/url" it should not be ac ...

Enhance the database with partial updates using the patch method in Django Rest Framework

I have a model called CustomUser that extends the AbstractUser class. class CustomUser(AbstractUser): detail = models.JSONField(default=dict) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=Tr ...

Generating grid-style buttons dynamically using jQuery Mobile

I am in need of assistance to create a dynamic grid using jQuery Mobile. The grid should consist of buttons with either 'onclick' or 'href' functionality. The number of buttons should be generated dynamically at runtime. Specifically, I ...

Have the quotes within my markup been replaced with HTML entities?

Currently, I am working on a content page that uses a master page which includes a text box and a button. My goal is to have the button execute some JavaScript code before performing any other actions. At the moment, I am in the testing phase of this JavaS ...