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 manually upon clicking the 'pick another' button. Any guidance or advice on how to achieve this would be highly appreciated.

Random.vue

<template>
  <div class="details" v-for="item in items" v-bind:key="item.id">
    <div class="details-primary u-center-text">
      <h1 class="heading-secondary">{{item.name}}</h1>
      <p class="tagline--main">{{item.tagline}}</p>
    </div>
    <div class="details-secondary u-margin-top-big">
      <div class="info">
        <span class="info__detail info--title">Vol</span>
        <span class="info__detail info--spec">{{item.abv}}%</span>
      </div>
      <img class="details-image" :src='item.image_url' alt="">
      <div class="info">
        <span class="info__detail info--title">Amount</span>
        <span class="info__detail info--spec">1ltr</span>
      </div>
    </div>
  </div>
  <div class="rand-gen">
    <a href="" class="btn">Pick another</a>
  </div>
</template>

<script lang="ts">
import {Options, Vue} from 'vue-class-component'
import axios from 'axios';

@Options({
  data() {
    return{
      items: []
    }
  },

  mounted() {
    axios.get('https://api.punkapi.com/v2/beers/random')
    .then(res => this.items = res.data)
    .catch(err => console.log(err));
  }
})

export default class Random extends Vue {}
</script>

Answer №1

Ensure to include the @click function as well as the method

This is how your html should look like

<a href="" class="btn" @click="generate">Choose another</a>

Here is the corresponding method

methods: {
  generate() {
     //insert your code here
  }
}

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

Issue with Angular: Mobile view toggle button in the navbar is unresponsive

While the dropdowns are functioning correctly in web mode, the navbar toggle isn't working as expected in small screens or mobile mode. I've been trying to figure out the issue by referring to code from CodePen that I am learning from. Despite i ...

Ways to delay the inner function's output?

Need help with making a function return only after its inner function is called. See below for the code snippet - function x() { function y() { // Inner function logic } return result; // This should be returned only after function y is ca ...

What precautions can I take to safely and securely extend event handling?

I am currently developing a small JavaScript library that includes components requiring "messages" based on specific page events, which allow users to define response functions. I need to access general events like onkeydown and let users determine how eac ...

How to Use TypeScript to Disable Href in Angular

I've encountered a challenge with disabling an href link using Angular and Typescript, and I'm unsure if my current approach is the right one. Is there a more optimal way to achieve something like this? I would like it to resemble the red circle ...

Is there a way to conceal the loading screen until the website has completely loaded?

I've been working on my personal portfolio/website and encountered a bug that I can't seem to fix on my own. The issue is with the logo (aa) and text under it showing even after the content page has fully loaded, taking around 3 seconds to hide. ...

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

What is the best way to reference a div link from a different PHP file?

Struggling to access a page div from another php file, I've tried calling it using (found online) admin.php#changepass Here's an example of my HTML code: <div id="changepass" class="w3-container city" style="display:none"> <form name ...

Error encountered: "Instance variable for Apex chart not defined while attempting to update charts with updateOptions."

I have integrated Apexcharts to create charts within my application. The initial data loads perfectly upon onload, but when applying a filter, I face an issue where the charts need to be refreshed or updated with the new filtered data. I attempted to use t ...

Tips for incorporating animated features into a bar graph using jQuery

How can I create a dynamic animated bar graph using jQuery? I am looking to make the bar slide up from the bottom, incorporating images for both the bar and background. I have already set the positioning in CSS and now need to add animation to make the bar ...

Smoothly automate horizontal scrolling using JavaScript

My programming journey involved creating a code snippet that automatically scrolls paragraphs horizontally, giving it the appearance of "Breaking News" updates on popular websites. The Javascript script I implemented performs automatic scrolling, but once ...

Angular 13: Issue with Http Interceptor Not Completing Request

In my app, I have implemented a HtppInterceptor to manage a progress bar that starts and stops for most Http requests. However, I encountered an issue with certain api calls where the HttpHandler never finalizes, causing the progress bar to keep running in ...

Displaying the age figure in JSX code with a red and bold formatting

I have a webpage with a button labeled "Increase Age". Every time this button is clicked, the person's age increases. How can I ensure that once the age surpasses 10, it is displayed in bold text on a red background? This should be implemented below t ...

Error message found: "Uncaught TypeError: e[n] is undefined while setting up redux store in a reactjs application

Delving into the world of Redux for the first time, I decided to tackle the Todo List example from the official redux.js.org website. After testing the code, everything seemed to be working fine with the redux store initialized only with the reducer as a p ...

The issue with dynamic rendering of HTML in Vue.js persists

new Vue({ el: '#application', data: { currencies: [ { 'name': 'Dollar', 'sign': '&#36;' }, { 'name': 'Euro', ...

Navigating the use of a getter property key within a generic method signature

What I want to do is create a class with descendants that have a method signature that can adapt based on a compile-time fixed property, which can also be overridden. Here's an example: class Parent { public get config() { return { foo: & ...

Why am I receiving an undefined value when I try to log the createdAnimal?

My main goal with this code is to successfully console.log(createdAnimal) and have the objectAnimal with specific parameters printed out. The following code snippet demonstrates the desired parameters: animalMaker('cat','flying',true); ...

Waiting for a method to finish in Node.js/Javascript

Currently, I am in the process of creating a trade bot for Steam. However, I have encountered an issue where the for-loop does not wait for the method inside it to finish before moving on to the next iteration. As a result, the code is not functioning as i ...

Using JavaScript onChange event with ModelChoiceField arguments

In my Django project, I have a Students model with various fields. I created a ModelChoiceField form allowing users to select a record from the Students table via a dropdown. forms.py: class StudentChoiceField(forms.Form): students = forms.ModelChoic ...

Toggle display of divID using Javascript - Conceal when new heading is unveiled

At the moment, I have implemented a feature where clicking on a title reveals its corresponding information. If another title is clicked, it opens either above or below the previously opened title. And if a title is clicked again, it becomes hidden. But ...

Showcase JSON data within a designated div

As someone new to HTML, JavaScript and Vue, I'm unsure if my issue is specific to Vue or can be resolved with some JavaScript magic. I have a Node.js based service with a UI built in Vue.js. The page content is generated from a markdown editor which ...