Struggling to retrieve unpredictable data in a Vue.js component

Help! I'm trying to randomly display one of these names in my HTML, but I can't seem to make it work:

Vue.component('modal', {
  template: '#modal-template',
 data: {
    items: [
      { name: 'Elena' },
      { name: 'Ares' }
     ]
 }, nowName : "",

 created () {
    const idx = Math.floor(Math.random() * this.items.length);
    this.nowName = this.items[idx]
  }
})

I've been struggling with my Vue code. I'm not sure if it's correct and if I can retrieve the random name using {{ nowName }}. I've tried different methods and functions in data, but nothing seems to give me a random result.

Answer №1

Have you considered whether the function is truly returning a random item? Keep in mind that idx will always be an integer value between 0 and this.items.length (either 0 or 1). Take for example, when running the code snippet below 10 times:

const items = [
  { name: 'You' },
  { name: 'Leonidas' }
];
new Array(10).fill(null).forEach((num) => {
  const idx = Math.floor(Math.random() * items.length);
  console.log(items[idx]);
});

nowName does not seem to be located within the data() function, which is typically where it should be. Could this be causing your issue?

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

How can I format the input type number with a thousand separator as 123.456.789?

When entering the number 123456, I want to see 123.456 displayed in the input field. I tried using my code, but it displays 123,456 instead. Is there a way to ensure that the thousand separator is a dot and not a comma? You can view my code at this link ...

What is the best way to generate a random item when a button is clicked?

I'm currently working on a feature in my component that generates a random item each time I access the designated page. While the functionality is set to automatically refresh and showcase a new random item, I am now looking to trigger this action man ...

execute the command only if all ava tests succeed

I'm working on creating an npm script that will execute Ava, and if it is successful, will then run another deploy command. Is there a way to obtain the result of an Ava test in JavaScript, or to save it to a file or pass it to a subsequent command? ...

having trouble compiling a react js file with webpack

One of my files, app.js, contains the following code snippet: handlePageClick = (data) => { let selected = data.selected; let offset = Math.ceil(selected * this.props.perPage); this.setState({offset: offset}, () => { this.setStat ...

Fixing an erroneous value that has been dragged into the drop function with Jquery

I am encountering an issue with my codes and need some assistance in identifying the problem. The data is being dynamically loaded from the database, and I am using a foreach loop to display all items in a draggable div. The issue arises when I drag an it ...

Why is my comment being saved multiple times? Why does Laravel 8 and Vue.js save comments multiple times?

This file contains my Vue comment component. <div> <button @click="getComments()" class="btn btn-primary"> Load Comments Post ID {{ post.id }} </button> <!-- Button trigger modal --> < ...

Unexpected "<" and dual output in jade include seem to defy explanation

i am currently redesigning my website to incorporate dynamic includes. These includes are pre-rendered on the server and then passed to res.render() however, I am encountering unexpected occurrences of < and > on the page, along with the issue of th ...

Troubleshooting Issue with Filtering Nested Object Array Based on Property

At the core of my data structure lies an array of orders, each containing an array of line items. These line items, in turn, are associated with their respective categories. I am currently attempting to filter the order array based on the category ID of th ...

Create personalized CustomElements in real-time

I developed a helper function to dynamically set up all CustomElements: let moduleDefaults = new Map(); let customElementsMap = new Map(); const registerComponents = () => { // ^ Check for .ce files -> then register components for (const [ke ...

Instructions on transforming an img into an Image component within next.js

I have successfully implemented all the logic in this component, tailored to the <img> tag. Now, I am aiming to apply the same logic to the Image component. However, when attempting to do so, I encounter an error. TypeError: Failed to construct &apos ...

Mastering parameter passing in Node.js functions: A comprehensive guide

As I embark on my journey with node js (refer to the question), please be patient as I navigate through this new territory. To clarify my query, I have developed a function to be invoked in another JS file: exports.test = function(req, res){ connection ...

What is the method for incorporating backdrop, escape, and header close triggers in a Bootstrap-Vue modal?

Currently, I am utilizing the bootstrap-vue modal in my project. I now have a requirement to implement validation when a user attempts to close the modal. Specifically, I need to display a confirmation message asking, "Are you sure you want to close withou ...

Tips for resolving the error message "An issue occurred with the skill's response" within the Alexa Developer Console

Looking to develop a basic Alexa app where users can interact with voice commands, but encountering an issue with the response in the Test tab of Alexa Developer Console. The error message states "There was a problem with the requested skill's respons ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Is it possible to asynchronously access a JSON object that has been retrieved from a local file on a global scale using the XMLHttpRequest method and

Having some trouble manipulating data from a local JSON file using this technique (no jQuery) as I can't seem to access the object on a global scale: var actual_JSON; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.o ...

Looking for a way to connect a background image in Vue CLI?

When running the code below, I encounter an issue. The code runs properly but the images are not displaying and instead showing the URL as unknown. How can I fix this problem? The images definitely exist. <template> <div class="slider">< ...

Error in npm installation: expected version "0.15.7" but received an empty string on the new Vite project

After setting up a new vite project, I encountered an error while trying to run npm install. Node.js version: 16.17.0 NPM version: 8.15.0 npm ERR! C:\xxx\GIT\NewTestProject\node_modules\esbuild\install.js:93 npm ERR! thr ...

Controller unable to properly increment values

$scope.isChecked = function(id){ var i=0,j=0,k=0; //$scope.abc[i].usertype[j].keywords[0].key_bool=true; if($scope.abc[i].type_selected == true){ while($scope.abc[i].usertype.length){ while($scope.abc[i].userty ...

Stop the Bootstrap 5 accordion from expanding when the spacebar is pressed in the header text input

Within my React app using react-bootstrap, I have implemented an accordion component that expands or collapses based on the user's interaction with a text input located in the AccordianHeader component. Interestingly, whenever the spacebar is released ...

What is the process for deploying a next.js application with a custom express backend to a VPS or Heroku platform?

Does anyone have advice on deploying a next.js application with a custom express backend to either a VPS or Heroku? ...