How can I refresh a Vue.js component when a prop changes?

Initially, I utilize a random number generator to create numbers that will be used in my api call

created() {
for (let i = 0; i < this.cellNumber; i++) {
  this.rng.push(Math.floor(Math.random() * 671 + 1));
}

These generated numbers are stored in an array called rng. I am displaying a component named Cell using the v-for directive

    <div v-for="x in rng" :key="x">
      <div class="col-sm-12">
        <Cell class="cells" :id="rng[x - 1]"></Cell>
      </div>
    </div>

The intention is to pass each element 'x' in rng to the Cell component, but despite generating the numbers, they are not being passed to the component. However, if I manually input numbers into the array, then the elements are successfully passed to the Cell component. What would be the most effective approach to overcome this issue? It seems likely that the calculations finish after the component is rendered, raising the question of how to update the component once the prop changes. I attempted using a watch function, but it did not resolve the issue.

Appreciate any guidance on this matter!

Answer №1

Can you explain the purpose of using this line :id="rng[x - 1]"?

After recreating the example, it seems like passing the element x to Cell is a straightforward process.

If your intention was simply to pass x as a prop, then the correct syntax would be:

<div v-for="x in rng" :key="x">
  <div class="col-sm-12">
    <Cell class="cells" :id="x"></Cell>
  </div>
</div>

You can view the updated code here.


Considering that the generated numbers are quite large, the line mentioned earlier may not function correctly (element does not exist):

:id="rng[x - 1]" //if x is 231 ---> rng[230]

This scenario is akin to attempting to access an element with an index of 230 within an array containing only 10 elements.


Note that there might be duplicated numbers - hence, using x as the key is advised against. It could be replaced with the index value for better results:

<div v-for="(x, index) in rng" :key="index">
  <div class="col-sm-12">
    <Cell class="cells" :id="x"></Cell>
  </div>
</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

Guide on displaying the appropriate child "div" with jQuery?

I am facing a challenge with my two dependent dropdowns that toggle the visibility of divs based on user input. The first div is functioning correctly, however, every time the user makes a selection in the second div, it impacts the first div. $(docume ...

Error: Unable to locate the tslint command

After attempting to utilize tslint --fix, I encountered the error message bash: tslint: command not found.... To install tslint, I ran the following command: yarn global add tslint typescript. The operating system on my machine is Centos 7. ...

I am experiencing an issue where my application, built using NodeJS, Express, and Javascript, is failing to insert form data into the database despite

I am facing a challenge with my app's MVC design pattern where I am unable to insert form information into the corresponding table in the database. Despite installing the body-parser package via npm, the form is not functioning as expected. Can anyone ...

Every time I switch views using the router in vue.js, my three.js canvas gets replicated

After creating a Vue.js integrated with three.js application, I encountered an issue with the canvas getting duplicated every time I opened the view containing the three.js application. The canvas remained visible below the new view, as shown in this image ...

Experimenting with a function invoked from a jQuery AJAX callback using Jasmine testing framework

Currently, I'm working on a function that utilizes an AJAX call to interact with a service. My main goal is to ensure the displayError function is triggered in case of a failure. The ajaxCall function is set up to accept a URL parameter. When the req ...

The Google Picker API encounters a server error when attempting to retrieve the OAuth token after being released as a private add-on

Recently, I encountered a puzzling issue with my script that utilizes the Google Picker API. During testing, everything worked flawlessly until I decided to publish it as a private add-on. From that point on, the script's getOAuthToken function starte ...

A Guide to Testing Directives in Angular 2: Unit Testing Tips

Issue: My goal is to perform unit testing on an Angular 2 directive to ensure proper compilation. In the context of Angular 1, one could utilize the$compile(angular.element(myElement) service followed by calling $scope.$digest(). I am specifically looking ...

Searching for a value within an array of objects using JavaScript: The ultimate guide

Similar Question: Locate specific object by id within a JavaScript objects array What is the best way to determine if a value exists in a given JavaScript array? For instance: var arr = [ {id: 1, color: 'blue'}, {id: 2, colo ...

JavaScript example: Defining a variable using bitwise OR operator for encoding purposes

Today I came across some JavaScript code that involves bitwise operations, but my knowledge on the topic is limited. Despite searching online for explanations, I'm still unable to grasp the concept. Can someone provide insight into the following code ...

Guide to creating a nested list using the jQuery :header selector

Here is the structure of my html: <h1 id="header1">H1</h1> <p>Lorem ipsum</p> <h2 id="header2">H2</h2> <p>lorem ipsum</p> <h2 id="header3">H2</h2> <p>lorem upsum</p ...

Issue with ngStyle function in Internet Explorer

Within my Angular 4 application, I have defined styles as shown below: [ngStyle]="{'border': getInterleaveColor(i)}" The following function is also included: getInterleaveColor(auditNumber) { var borderProperties = '2px solid'; ...

How to retrieve client's hostname using Node and Express

How can the client's hostname be retrieved in a Node / Express server? Is there a method similar to req.connection.remoteAddress that can be used to obtain the client's hostname? ...

Identify all the CHECKBOX elements that are visible and not concealed

On my page, I have various checkboxes - some with hidden=true and others with hidden=false attributes. Despite trying to use a selector or jQuery to locate checkboxes with the hidden property, I am still facing some challenges. My goal is to differentiate ...

Comparing parameters between two functions in Javascript: a step-by-step guide

I am currently working on solving this problem: var name; var totalScore; var gamesPlayed; var player; var score; // Creating the game player object function makeGamePlayer(name, totalScore, ga ...

Tips for dividing the elements of an array by 4 using Javascript or ReactJS

I have a large array of items that I need to organize into 4 sections in order to improve the display on my user interface. The array contains up to 20 objects, and my objective is to create 4 separate arrays each containing 5 objects. let attributes = [ ...

How to import a template from a different webpage in AngularJS

I have a situation where I need to include a template from one HTML page into another because they are both lengthy and it's not practical to keep them on the same page. Therefore, I have decided to separate them for better organization. Here is an ov ...

In the world of Express, the res.write function showcases the magic of HTML elements contained within

Currently diving into web app development, I have ventured into using express and implemented the following code snippet: app.post("/", function(req, res) { var crypto = req.body.crypto; var fiat = req.body.fiat; var amount = req.body.amount; va ...

Issues with dynamically generating buttons using Ajax and Javascript technology

In order to dynamically create buttons based on the contents of a text file during the onload event, I have written a JavaScript function. However, despite being able to read the file and using alert messages to verify the correctness of the variable &apos ...

Can we rely on the render method to display the updated state immediately after invoking setState within

Is it guaranteed that the state will exist in the render method if I call setState within componentWillMount without using a callback? According to Facebook, "componentWillMount is called before render(), therefore calling setState() synchronously in this ...

Leveraging an array to store data within highcharts

When I input the data directly in high charts, it works perfectly: $(function () { $('#container').highcharts({ title: { text: 'Monthly Average Temperature', x: -20 //center }, subtit ...