Unexpected behavior encountered when using v-bind in conjunction with Math.random

I'm exploring the concept of generating random styles for an array of spans within a Vue component. By breaking down the message and utilizing v-for, I aim to showcase individual words in separate spans.

const textFx = Vue.component('text-fx', {
  template: '<div class="textFx"><span v-bind:style="{opacity: Math.random().toFixed(2)}" v-for="words in wordArray">{{words}}</span></div>',
  props:['message'],
  data: function() {
    return {
      wordArray: []
    }
  },
  methods: {
    setMessage: function() {
        this.wordArray = this.parseMessage;
    },
  },
  computed: {
    parseMessage: function() {
      var temp = this.message.split(" ");
      for(var i = 0; i < temp.length - 1; i++) {
        temp[i] += " ";
      }
      return temp;
    },
  },
  created: function() {
    this.setMessage();
  }
});

The code snippet shows the application of randomly setting opacity for each span. Though it functions as expected in the example, hard-coding every random property is not ideal. Instead, employing a method or computed property is preferred. Here's an attempt at integrating a dynamic approach:

computedStyle: function() {
      var o = Math.random().toFixed(2);
      return {
        'opacity': o,
      };
    }

This revised implementation involves adding the computed style to the spans like so:

'<div class="textFx"><span v-bind:style="computedStyle" v-for="words in wordArray">{{words}}</span></div>',

While the method does provide a random opacity value, it assigns the same randomness to all spans instead of generating individual values as seen with the hard-coded version.

To achieve randomization for each rendered span, how can I structure the component to accommodate a method or computed property that recalculates the Math.random value per span?

Answer №1

When it comes to computed properties, they will only update if there is a change in one of the data properties they depend on. In the case of your computedStyle, since it doesn't rely on any other properties, its calculation function is only executed once. This means that the computed value will remain constant even after multiple references.

If you find yourself in a similar situation, where you need dynamic styling, consider defining a method that returns the style object instead:

methods: {
  getComputedStyle() {
    return { opacity: Math.random().toFixed(2) };
  }
}

Then, you can simply call this method when binding the style like this:

<span v-bind:style="getComputedStyle()"></span>

Check out this working example on CodePen.

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

Positioning Images with CSS Backgrounds

I am looking to create a fluid background that stretches widthwise, while adjusting its height based on the content. If the content is smaller, I want the background to be truncated. However, if there is a lot of information, I would like the background to ...

Utilizing Typescript to explicitly define function parameter types

Currently, I am working on: function fn(arg) { const foo = arg as SomeType; ... } Is there a way to perform type casting directly in the function argument? For instance, something like function fn(arg as SomeType) Here is an illustration: Promise.r ...

What is the reason for DialogContent displaying a scroll bar instead of expanding further when nested Grids with spacing are included?

My current project involves working on a form displayed in a dialog window. To adjust the layout of the form's fields, I utilize multiple Grid elements nested within another Grid. However, I've encountered an issue where adding any spacing to the ...

Different methods for incorporating script-specific data into markup

How can we include extra meta data in HTML code to support client-side javascript functionality? Let's consider some straightforward examples: A list of contacts that, when clicked, displays their location on a map. For instance, how can we link la ...

Issue: Utilized more hooks than in the previous render cycle

After the initial load of a component that renders and makes data calls on the client side, everything works fine. However, when clicking a "see more" button to make another call, an error occurs in the console indicating that there are too many hooks be ...

Update data dynamically on a div element using AngularJS controller and ng-repeat

I am currently navigating my way through Angular JS and expanding my knowledge on it. I have a div set up to load data from a JSON file upon startup using a controller with the following code, but now I am looking to refresh it whenever the JSON object cha ...

Getting map data from Mapbox and displaying it on an HTML page

I have been working with Mapbox GL JS and successfully retrieved data in the console. However, I am facing issues when trying to display this data on an HTML page. Can anyone assist me with this problem? I specifically need the data inside mapdata to be sh ...

Putting a link on a button exclusively

Currently, I am utilizing Bootstrap 5 to develop a website. One of the pages features a header that consists of an image with text and a button overlay. The intended functionality is for users to be redirected to another site when clicking on the button. ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...

Start up a server using Angular along with Node.js and Express framework

I am encountering an issue with configuring Express as a server in my Angular application. The app loads without any issues when accessing the HOME route, but when trying to access another route, I receive an error message: Cannot GET / This is how I hav ...

Issues with Webpack - Unable to locate 'crypto', 'http', and 'https' in Vue.js

Question Background I'm currently working on integrating Wallet Connect into our Vue.js project following the instructions provided in this documentation: . I have installed it using the command below: import it in my js file import Web3 from ' ...

Tips for resolving issues with the header and scrolling content

I am new to CSS and I understand that it is quite simple: Question: I have a sample HTML page below, and when I scroll the page, the header does not stay fixed in one place. What am I missing here? Please assist. window.onscroll = function() { myFunc ...

Tips for combining two sets of data from Facebook Graph API (in JSON format)

In order to overcome the limitation of Facebook graph API only returning 100 user likes ("/me/likes?limit=100"), I devised a loop that continues until all likes are retrieved. This results in separate graph API response objects, which need to be merged i ...

Issue with select box component not functioning properly when being displayed in laravel view mode

I'm struggling with a logic error in Laravel concerning the view component. I have a select box whose value is sourced from a database table. However, only the last value of the table is being displayed when I run the code. Below are my component and ...

Find the final element that does not include a particular class

Looking for the best way to identify the last item in a list without a specific class? Learn how to write code that can check for the absence of a class name. $('ul li:last') $('ul li:not(.special)') ...

Words curl around the far-off entity

Challenge I'm currently working on a project where I need to place an interactive info box next to other elements in the DOM. However, I've encountered an issue with text from one paragraph wrapping around the text in a separate div, even though ...

The alignment of the text within the 'li' element is not as anticipated

CSS code: ul { list-style: none; padding:0; margin:0; } li { padding-left: 1em; text-indent: -.7em; } li:before { content: "• "; color: #28B779; /* or any other color you like */ font-size:2em; } <ul> <li ...

Error: The terminal reports that the property 'then' cannot be found on the data type 'false' while trying to compile an Angular application

In my Angular application, which I initiate through the terminal with the command ng serve, I am encountering build errors that are showing in red on the terminal screen. ✔ Compiled successfully. ⠋ Generating browser application bundles... Error: s ...

The Node.js timestamp is later than the current date of the client

When storing data in MongoDB with the recording date, I utilize new Date() in Node.js and return that date with an AJAX response. To calculate the elapsed time from when the data was stored in MongoDB, I create a new date on the client-side. Then, I determ ...

What is the best way to conceal an element by clicking anywhere other than on the element itself?

Currently, I am utilizing jQuery's toggle method to display or hide a page element when another specific page element is clicked. jQuery('a#mobile-search-icon).click(function(){ jQuery('#searchBox').toggle('slow'); }); ...