Attempting to display a randomly selected element from an array upon clicking a button, utilizing axios and a local JSON file. Is there something crucial that I am overlooking?

I have figured out how to display the entire array in a random order but I am struggling to render just one element of the array. Another issue I am facing is showing the complete JSON object instead of only the quote text.

Below is the HTML code:

<template>
  <div>
    <button v-on:click="getTeacupData">Get Teacup Data</button>
    <!-- <div>{{ teacupDataList }}</div> -->
    <div
      v-for="teacupData in teacupDataList"
      :key="teacupData.quote"
      class="teacup-data"
    >
      <div>
        <span class="quote">
          {{
            teacupDataList[Math.floor(Math.random() * teacupData.quote.length)]
          }}</span
        >
      </div>
    </div>
  </div>
</template>

And here is the script:

<script>
import axios from 'axios'

export default {
  name: 'Teacup',
  data() {
    return {
      teacupDataList: []
    }
  },
  methods: {
    getTeacupData() {
      axios.get('/teacupProph.json').then((response) => {
        this.teacupDataList = response.data
      })
    }
  }
}
</script>

Answer №1

Create a computed property named randomSaying in the following manner :

<script>
import axios from 'axios'

export default {
  name: 'Teapot',
  data() {
    return {
      teapotDataList: []
    }
  },
 computed:{
  randomSaying(){
    const randomIndex = Math.floor(Math.random() * this.teapotDataList.length)
     return this.teapotDataList[randomIndex] ? this.teapotDataList[randomIndex].saying : ""
   }
  },
  methods: {
    fetchTeapotData() {
      axios.get('/teapotWisdom.json').then((response) => {
        this.teapotDataList = response.data
      })
    }
  }
}
</script>

Avoid using a v-for loop in the template, simply call the computed property like so :

<template>
  <div>
    <button v-on:click="fetchTeapotData">Get Teapot Data</button>

      <div>
        <span class="saying">
          {{
            randomSaying
          }}</span>
      </div>

  </div>
</template>

Note:

Ensure your JSON file is stored within the components folder and can be accessed via axios('./teapotWisdom.json'). Additionally, correct the event handler to @click instead of @:click. For reference, see this example code.

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

The functionality of ng-click and ng-submit seems to be malfunctioning

I am currently facing an issue with my Angular application and PhoneGap. I have a login form along with a login controller set up, but for some reason, the ng-submit function is not working as expected. When the submit button calls the formConnexion() func ...

The absence of the 'profileStore' property is noticed in the '{}' type, which is necessary in the 'Readonly<AppProps>' type according to TypeScript error code ts(2741)

I'm currently using MobX React with TypeScript Why am I getting an error with <MainNote/>? Do I just need to set default props? https://i.stack.imgur.com/5L5bq.png The error message states: Property 'profileStore' is missing in typ ...

Invoking a static method within a cshtml document

I am currently working on implementing a clickable DIV within a vertical tab panel. My goal is to have a specific static method called when the DIV is clicked. Here is what I have done: <div class="tabbable tabs-left"> <ul class="nav nav-tabs"> ...

Exploring PostgreSQL Nested JSON Queries

In my PostgreSQL database version 9.3.4, I have a column of type JSON named "person" with data stored in the following format: {dogs: [{breed: <>, name: <>}, {breed: <>, name: <>}]}. My goal is to extract the breed of the dog at ind ...

Issue: Module 'ansi-styles' not found when using AngularJS and Yeoman generator

Previously my code was functioning perfectly, but now it seems to have suddenly stopped working. Attempting yo angular:route api resulted in the following error message: Error: Cannot find module 'ansi-styles' at Function.Module._resolveFilen ...

one component shares information with another component through a single controller

My goal is for the component dbServerTable to provide data to dbServerInfoSidebar whenever a list item from dbServerTable's template is clicked. However, I am experiencing an issue where no data is being displayed in dbServerInfoSidebar. (function(an ...

A Guide on Accessing Promise Results in AngularJS

In my code, I am using a controller to retrieve information from SharePoint. While debugging, I noticed that the value of data.d.UserProfileProperties.results[115].Value is what I need to display in the view. However, I am struggling to extract that value ...

using Javascript to eliminate necessary tags from concealed tabs

My goal is to dynamically remove the required tag from fields in hidden tabs when a tab is clicked using JavaScript. The presence of the required tag on unused fields causes issues with form submission, preventing data insertion into the database. Here&apo ...

Deleting a row from the table with a single click on the X icon

Is there a way to delete individual rows in a table by clicking on a close icon instead of removing all rows at once? Additionally, I am looking for a better method to display rows in a table. You can view my current implementation here: link -> jsfiddl ...

Retrieve the index of the item that has been selected in a dropdown list

<select ng-click="getIndex($index)" size="14" ng-model="playlist.fileSelected" ng-options="saveFile for saveFile in playlist.playlist"></select> When I try to access $index, it shows up as undefined. Is there a way to retrieve the index of the ...

Experiencing a ResponseStatusLine issue while trying to download a .json file from an API site

Recently, I set out to develop a small app using the Discogs API for my own personal use. The aim was to easily search for individual artists and their albums. Thanks to an unofficial Discogs C# app, I was able to achieve this successfully. However, I enco ...

Encountering a Vue npm installation issue

When following a tutorial, version information can be crucial. [root@localhost my-project]# node -v v6.11.3 [root@localhost my-project]# npm -v 3.10.10 [root@localhost my-project]# vue --version 2.9.2 [root@localhost my-project]# cat /etc/redhat-releas ...

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

Retrieve information from server using JavaScript/jQuery and present it on the page

Imagine having a JavaScript file stored in a specific directory on your computer. In that same directory, there is a folder named 'server' which contains three text files. Now, the task is to showcase all three text files (from the 'server& ...

The art of implementing a search feature to remember previous searches in Vue.js

I have two vuejs pages below. On my list page, I have implemented filters for searching by user name and email. The filter is functioning properly, but the issue arises when I type something in the search box, perform a search, click on the edit user link, ...

Is it possible to retrieve the final digit from a URL using NUXT/Vue?

My dilemma involves utilizing the SWAPI API to display a single result, whether it be a person or a planet. However, instead of providing a direct ID for each item, the API returns a complete URL in this format: "url": "http://swapi.dev/api/ ...

Passing a value to a component to delete a table row in ReactJS using Material UI

My task is to delete a specific table row after clicking. I have two components and have already written a function, handleDelete(), to remove a row from the table. The issue is that whenever I click, it always deletes the last row instead of the one I cli ...

Render a specific number of instances of a react component

Below is a code snippet that I am working with: import React, { Component } from 'react'; import {Button} from "@material-ui/core"; import Selector from "./Selector" class Trigger extends Component { constructor(props) { super(props); ...

I'm having trouble figuring out the correct way to serialize POJOs into JSON data for the ClientRequest. It seems like I can't locate a writer for the content

When creating JUnit test cases for a REST service (RESTeasy), I encountered an issue: @Test public void a100_insertAddressTest() throws Exception { Address addr = new Address(1, "testStreet", "1", (short) 1234, "testCity"); ClientRequest re ...

JavaScript code for transitioning between a thumbnail and a full-width image header on a webpage

I am looking to create transitions in NextJs that involve a smooth shift from a thumbnail image to a full-screen header when clicking on a project from the home page. I prefer utilizing internal routing rather than React Router, but I am open to using that ...