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

Is there a way to prevent redirection to the homepage after submitting a login form?

Having trouble with my Single Page application: every time I refresh the page after rendering the login form, it goes back to the homepage. How can I prevent this and make sure the page stays on the login form even after a refresh? This is what my homepag ...

Leveraging viewbag information in combination with jQuery JSON techniques

I have a desire to utilize my ViewBag within a JavaScript array. After researching on using viewbag with jquery asp.net mvc 3, I believe I found the code that suits my needs: @model MyViewModel <script type="text/javascript"> var model = @Html. ...

Obtain details regarding a worker's collision

This code snippet is being used to manage cluster crashes within a node application cluster.on('exit', function (worker, code, signal) { console.log("error in cluster",worker); console.log("cluster code",code); console.l ...

get an array of JSON data from a VueJS fetch or axios.get request

I can't seem to figure out this issue. The code I have below is giving me some trouble. When I try to run it, I keep getting the following error message: Access to XMLHttpRequest at 'URL' from origin 'http://localhost:8000' has b ...

Strange sequence of results coming from Vue.js

methods: { ShowWindow: function(QueryID) { this.$data.ID = QueryID; if(this.GetData()) { console.log("asdasd") } document.querySelector("#EditWindow").style.visibility = "visi ...

The Jquery Index() method often results in a return value of -

I have developed a function in JavaScript that creates HTML content. Within the test(test1) function, I am checking if test1.Test__c is null and changing the color accordingly. The line ".table-striped > tbody > tr.testcss" is responsible for changin ...

How can I retrieve the /api/auth/me resource serverside using the NextJS AppRouter?

I am looking to implement app router in my Next.js project and have encountered an issue. In order for my app to function properly, I need to make a call to /api/auth/me which will return either a user object or null if the user is not logged in. To achiev ...

The slides in Swiperjs are having trouble moving smoothly

I am experiencing some challenges with swiperjs where the slides are not snapping to the next slide and I am unable to fetch the active index from them. Below is a snippet of my code where I am using typescript, swiperjs version 6.84, and the Ionic frame ...

Having issues transferring the variable from JavaScript to PHP?

When attempting to pass a variable via AJAX request in JavaScript, I am encountering an issue where the variable is not being received in my PHP file. I'm unsure of where the problem lies. Can anyone help? JavaScript code var build = { m_count : ...

Switch up the Thumbnail Image based on the selected category

While testing a shopping site I created, I encountered an issue with changing the banners at the top of the page based on the category the user is viewing. This site is hosted on a server on my localhost, not using wordpress by the way. <div class=" ...

converting a CSV string into a JSON array using AngularJS

My data is in a comma-separated format: "HotelName","Remained","Date" "Maxx","4","Jun 26 2016" "Voyage","3","Jun 24 2016" I am looking to convert this into a JSON array as shown below. How can I achieve this using my JavaScript code? [ { HotelName ...

What is the time stamp format of 1651928421543667000?

Recently, I have encountered an issue with an API returning a timestamp as 1651928421543667000. Despite trying various PHP functions like strtotime(), datetime(), and strftime(), I am unable to find the correct format for it. Can anyone provide some guid ...

`Moving smoothly with a slider and then reversing direction`

I have implemented a range slider to control the value in an input field. The values can vary greatly, so I needed finer control for lower numbers that gradually expands for larger numbers. To address this issue, I utilized an easing equation based on the ...

Best practices for referencing attributes created with the data method in a Vue component

In my application, there is a section that displays a list of users along with a search box to filter names. The user information is fetched from a database and stored in app.users. I have created a component named 'user' to show the details of e ...

Creating dynamic bar chart visuals using Morris.js with JSON responses

Utilizing the morris.js library, I am extracting and plotting bar charts from data retrieved through a webservice. Issue: The format of my webservice URL is as follows: http://localhost:9999/hellowebservice/search?select=* I populate the select query ...

Laravel 6 does not support the mounting of Vuetable-2

Recently, I've been experimenting with incorporating the Vue component Vuetable-2 into my Laravel 6 project. Despite Vuetable-2 being created for version 5.4 of Laravel, I have a hunch that it should still function properly. Here's a snippet fro ...

Creating and fetching CSV files using PHP and AJAX

I have successfully created a PHP script that generates a CSV file for automatic download by the browser. The code below shows a working version with sample data for different car models. <?php $cars = array( array("Volvo",22,18), array("BMW",15,1 ...

JavaScript vanilla can be difficult to grasp, especially when it comes to

I'm experiencing a delay in displaying and hiding the mobile menu and table of contents section on my website when viewed on a mobile device. I'm using vanilla JavaScript to add and remove classes, but it's taking about one second for the me ...

Initiate Child Event within Parent Component

Before switching tabs in the parent component, I want the child tab to validate itself. My idea is to pass the onActive event from the parent to its children, <ClientInfo/> and <Details/>. This will allow the children to validate themselves a ...

How to choose an option from a dropdown menu using React

In a React application, I am creating a straightforward autocomplete feature. The code is outlined below. index.js import React from 'react'; import { render } from 'react-dom'; import Autocomplete from './Autocomplete'; co ...