Ways to set a random value to a data attribute from a specified array while using v-for in Vue.js?

In my main Vue instance, I have a data attribute that consists of an array containing 4 items:

var app = new Vue({
            el: '#app',
            efeitosAos: ['fade', 'flip-up', 'slide-up', 'zoom-in'],
            aos: 'fade-in'
}

This array contains the names of effects from the AOS library. My goal is to randomly select a value from this array and pass it to one of my components.

Each component is called within a v-for:

<post v-for="post, index in posts" :key="post.id" :post="post" :efeito="aos">
    {{randomizaAos()}}
</post>

Below is the structure of my component:

const post = {
   data: function(){
        return {
            duration: 1000,
            delay: 50,
        }
    },

    props: {
        efeito: '',
        post: {
            id: '',
            titulo: '',
            resumo: '',
            imagem: '',
        },
    },
    template: '\
        <section class="guarda-post" :data-aos="efeito" :data-aos-duration="duration" :data-aos-delay="delay">\
        <img :src="post.imagem" class="img-fluid">\
        <h4 class="titulo-post">{{post.titulo}}</h4>\
        <p>{{post.resumo}}</p>\
        </section>'
};

Within my component, there is a prop named efeito, which should receive the value of my data attribute aos from the main Vue instance. To handle this, I've implemented a method as follows:

methods:{
        randomizaAos: function(){
           var efeitoAleatorio = Math.floor(Math.random() * this.efeitosAos.length);
           this.aos = this.efeitosAos[efeitoAleatorio];
           console.log(this.aos);
        }
}

The issue arises when I execute the randomizaAos method - it triggers an infinite loop, and I'm unsure why. Strangely enough, if I only include the console.log statement inside the method, I get exactly 4 messages, corresponding to the size of my posts array. However, once I introduce the Math calculations and assign the found value to my aos data, the method gets stuck in an infinite loop. What could be causing this behavior? Any insights would be appreciated.

Answer №1

Assign the efeito property value in the mounted lifecycle hook to prevent unnecessary re-rendering

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

Creating Dynamic HTML/DOM in Angular 14: A Guide for Adding New Items to a List

I am currently iterating through a list of items and displaying them within a div element. These items are rendered when the page initially loads. <button (click)="addCut()" mat-raised-button color="primary">Add New Cut</button ...

Error in AngularJs: [$injector:modulerr] Unable to create schemaForm module instance

Trying to integrate angular-schema-form into AngularJs Seed has been a challenge. Following the steps outlined in the angular-schema-form repository: view1.js 'use strict'; angular.module('myApp.view1', ['ngRoute', 'sc ...

Rgd: Double-Sided Horizontal Slide Control

While browsing the internet, I came across several examples of horizontal sliders with adjustable values. For example, if I set the maximum value as 100 and move the slider 10 sectors to the left, each sector would decrease by 10. What I am trying to ach ...

switching tabs on a webpage

My PHP page has a menu tab with tabs labeled as Dash and Project. The Dash tab contains a table displaying data. The scenario is that when I click on a row in the table within the Dash tab, it should navigate to the Project tab, where a simple form is disp ...

No spaces are being retrieved from the input field

After entering "test data" in the first input box and clicking the submit button, only "test" is displayed in another input box. The goal is to have "test data" appear in the script-generated input box as well. Sample HTML Code <input name="" type="te ...

Maintaining personalized variable values for individual connected clients in Node.js: What's the best approach?

I have recently started working with Node.js and I am using Visual Studio 2015 with the Basic Node.js Express 4 app template. After setting some values through a post request from the client, I noticed that when I open another tab and send another post re ...

What is the best way to merge two fetch requests in order to gather the required data?

If I want to create a website with details about movies, one crucial aspect is getting information on genres. However, there's a challenge in the main data request where genres are represented by IDs. I need to execute another query that includes thes ...

What is the best way to display HTML content inside a pop-over window?

How can I load popover content from another HTML file using templateUrl in AngularJS? Check out the demo below: HTML: <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8"/> <title>AngularJS Plunker& ...

What is the process for placing API routes within the new app directory of Next.js?

If you have a test API located at: pages\api\accounts\login.js, and are currently exploring the new app folder, which is still in its experimental phase in Next.js (as of today). Are you wondering if it's feasible to transfer your logi ...

How can a 'complete' event listener be executed for a custom function in JQuery/JavaScript?

Here is the code snippet I'm working with: $('.fblikes span').fblikecount(); $.fn.fblikecount = function(){ //Perform JSON XHR operations to retrieve FB like counts and update the page numbers } This code will cycle through all insta ...

Arranging and Filtering an Object Array Based on their Attributes

Here is an example of a JSON array called items: var items = [ { Id: "c1", config:{ url:"/c1", content: "c1 content", parentId: "p1", parentUrl: "/p1", parentContent: "p1 content", } }, { Id: "c2", ...

What methods are available to load sections of a complex SVG shape asynchronously?

I'm currently in the process of creating a website with a geographic map built using SVG, pulling data from OpenStreetMap. Due to its large size and potential for transformations such as zooming and moving, only a portion of it will be visible on the ...

Creating an array object in JavaScript is a straightforward process that involves using the array

Looking to achieve the following object list structure: myObj = {"foo":[1,2,3,4], "bar":[3,5,7,8]} Initial attempt was unsuccessful: var myObj = new Object(); myObj["foo"].push(1) myObj["foo"].push(2) #...etc Seeking guidance on the correct m ...

Popup window displaying website content upon DOM loading, ensuring compatibility across various browsers

I am facing a challenge with my HTML popup window where I need to add text after opening the window using a specific function: var win = window.open('private.php', data.sender_id , 'width=300,height=400'); win.win ...

Resolving the Enigma: Querying jQuery for Real-Time Validation and

I'm fairly new to jQuery and I'm facing a challenge in my registration form script. Specifically, I want to check if the entered username or email is already taken while the user is typing. Currently, this functionality works by making a json req ...

AngularJS ng-switch-trigger enclosed within its own ng-switch-wrapper

In my current project, I am working on switching between two buttons that act as their own triggers for the switch. To illustrate further: <span ng-switch on="patientSwitch"> <span ng-switch-when="edit"> <button ng-click="patien ...

Struggling to receive accurate data from every statement

I have an object (known as allUserInfo) that looks like this: Object { available_client_ids: Array[2] 0: "demo" 1: "4532t78" available_client_names: Array[2] 0: "Demo" 1: "Bobs Bakery" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Remove all stored data from localStorage and update the view in Backbone framework

Hi, currently I am using backbone localstorage and facing an issue where I need to clear the localstorage every time a user hits the search button. This will allow me to add new data to the localStorage without any conflicts. Additionally, I am attempting ...

Sending the entirety of a data object as props

Can you pass the entire data object as props in Vue? For instance Vue.component('comp', { props: ['allData'], template: '<div>{{allData.msg}}</div>' }) new Vue({ el: "#test", data: { msg: "Hello" } }) ...

Encountering a NaN outcome when summing values from various select options

I'm working on a project that involves adding up the prices based on the surface chosen by the user. I'm struggling with calculating the partial cost when the user's choice changes. totalSum.ts num: Calculation totalAmount: number cate ...