Show or hide a component based on a mouse click in Vue JS

After a prolonged absence from working with Vue JS, I find myself in the process of displaying a list of data with a button for each item. The goal is to conditionally render a component when a button is clicked.

I am wondering if there is a recommended approach by Vue for achieving this functionality. Should I be directly manipulating the DOM? The current implementation does not seem to be effective.

<template>
    <div v-for="data in list">
      {{ data.bar}}
      <button @click="handleClick">
        <div v-if="dataset.loading === 'true'">
          <loader/>
        </div>
        <div v-else>
      </button>
    </div>
</template>

<script setup>
    import { loader } from './components'

    const list = [{ foo: 'bar'}];
    
    const handleClick = (el) => {
        el.dataset.loading = 'true';
        setTimeout(3, () => el.dataset.loading = 'false');
    };
</script>

Answer №1

Discovery :

  • Upon observation, it was noted that there is no object in the list array with the key bar. It is suggested to use data.foo instead of data.bar.

Recommendations :

  • Whenever possible, it is advisable to include a :key with v-for.

  • Include a loading property in each object within the list array. This will enable dynamic behavior when setting the value for onClick.

Experience Live Demo :

new Vue({
  el: '#app',
  data: {
    list: [{ foo: 'bar', loading: false }]
  },
  methods: {
    handleClick(dataIndex) {
      this.list[dataIndex].loading = true;
      setTimeout(() => {
        this.list[dataIndex].loading = false;
      }, 2000);
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(data, index) in list" :key="index">
      {{ data.bar }}
      <button @click="handleClick(index)">
        <div v-if="data.loading">
          Loading Start
        </div>
        <div v-else> Loading Finish </div>
      </button>
    </div>
</div>

Answer №2

Ensure to apply ref on your list variable for it to be reactive. Additionally, you are trying to access a dataset variable that is not defined in your application.

Here's a method to address this issue by adding extra data to your list.


<script setup>
import {ref} from 'vue'

let list = ref([{ foo: 'bar', loading: 'true'}]);

const handleClick = (data) => {
    setTimeout(() => {
      data.loading = 'false'
    },1000);
};

</script>

<template>

    <div v-for="data in list" >
      {{ data.foo}}
      <button @click="handleClick(data)"> //you can also use a `ref` here.
        <div v-if="data.loading === 'true'">
          Your Loader Component
        </div>
        <div v-else> 
          Something else...
        </div>
      </button>
    </div>
</template>

For more information, refer to Template Refs documentation

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

What is the best way to incorporate an if else condition using the <?php if($loggedin): ?> statement within JavaScript code to display a button push or pop response from the server side?

I would like to verify this php if condition code ''<?php if($loggedin) : ?>'' inside JavaScript code in order to display one of the buttons, either push or pop. I want to keep this button hidden from the client side by embedding ...

Ways to update the entire MobX observable array with new values

When working with MobX, is there a way to update the values of an observable array without re-setting every value? At first glance, one might think the solution is: let arr = observable([]); autorun(() => { console.log('my array changed!') ...

Concentrating on div elements using React

Can the focus() method be used to focus on a div element or any other elements? I have added a tabIndex attribute to a div element: <div ref="dropdown" tabIndex="1"></div> When I click on it, I can see that it gets focused. However, I am att ...

When debugging in ASP MVC4, JavaScript will only evaluate HiddenFor once you've paused to inspect it

Struggling with evaluating a hidden field in JavaScript (ASP MVC4). I've set up a model in my View with a hidden input for one of the properties. @Html.HiddenFor(mdl => mdl.FilterByUser, new { @id = "filterByUserId" }) Within my Helper, I have a ...

Oops! There was a validation error as the duration was not formatted as a number. Please make sure to provide a valid numerical value for the duration field

When attempting to update data from a MongoDB database and checking the results on Postman, an error is encountered. The error reads as follows: "Error: ValidationError: duration: Cast to Number failed for value \"NaN\" at path \"duration&bs ...

Troubleshooting the Google OAuth 2.0 SAMEORIGIN Issue

Trying to bypass the SAMEORIGIN error while using Google's JavaScript API is a timeless challenge. Here is an example of what I have tried: let clientId = 'CLIENT_ID'; let apiKey = 'API_KEY'; let scopes = 'https://www.google ...

Trying to bring in components from directories above

I'm currently facing an issue with importing components from a parent directory into my project. My goal is to be able to use these components across multiple projects, which seems like the most straightforward approach. However, when I attempt this, ...

Select elements from a PHP loop

As part of my school project, I am developing a basic webshop. Currently, I am using a while loop to display featured products on the homepage. However, I now need to implement a shopping cart functionality. After a user clicks the "add to cart" button, th ...

Are you seeing a 'Connection refused! Is the selenium server started?' error while running VueJS Nightwatch E2E tests with ChromeDriver and Chrome?

My VueJS app is integrated with Nightwatch E2E tests. I recently set up user accounts and authentication, but now when I run the E2E tests, they fail inexplicably. Here is the output I receive: code/premium-poker-tools [master●] » npm run e2e > < ...

When using Axios to GET from a local PHP file, it only retrieves the code instead of running

I've run into an issue accessing the API as it has CORS disabled, requiring me to make requests on the server side. Currently, I'm using React and Axios to send a GET request to a local php file that should trigger cURL execution. However, instea ...

I can't figure out why I keep receiving the InvalidArgumentError for H.Map with Argument #0 [object Object]

I recently refactored the code taken from the Maps API for JavaScript "Working with React" section. As a beginner in React and currently learning it in school, I have to utilize functional components. The material provided guidance on class component syn ...

Integrating webpack with kafka-node for seamless communication between front

I am in the process of embedding a JavaScript code that I wrote into an HTML file. The script requires kafka-node to function properly, similar to the example provided on this link. To achieve this, I am using webpack to bundle everything together. I am fo ...

`A straightforward technique for establishing client-server communication using NodeJS`

Stumbling upon a valuable code snippet on GitHub for enabling straightforward server-client communication in NodeJS has been quite enlightening. Upon making some adjustments, the finalized structure of my code looks like this: The client (Jade + Javascri ...

How can I revert a date format using date-fns?

Greetings from Thailand! I have a question regarding the reverse formatting using date-fns. Is there a way to create a function that will change "saturday-9-september-2564" back to "2022-09-24" using date-fns? Any insights or methods on achieving this wo ...

Creating new rows dynamically with jQuery

In my current setup, there is a table with one row and two columns - a textbox and a button: $(function() { var i = 1; $('#add').click(function() { i++; $('#dyn').append('<tr id="row' + i + '">&l ...

Is it possible to exclude certain static files from being served in express.static?

const express = require('express'); const app = express(); app.use('/app', express.static(path.resolve(__dirname, './app'), { maxage: '600s' })) app.listen(9292, function(err){ if (err) console.log(err); ...

Sketch the borders of the element (animated)

Seeking a way to create a button with an animated border that looks like it is being drawn. Current progress involves some code, but it's not working smoothly with border-radius set. (keep an eye on the corners) https://codepen.io/anon/pen/MbWagQ & ...

Adjust the jQuery and PHP script to retrieve both the ID and text content to populate an OPTION element

I have a basic DROPDOWN list: <select class='form-control' id='builders' name='builder_id'> <option value="1">Java</option> <option value="2">Python</option> </select> I am looking ...

Nullify the unfulfilled fetch call

When a value is entered in the search bar on the webpage, it gets added to a URL and used to retrieve JSON data. Everything works smoothly, but if a value is inputted that the API doesn't have information for, a null response is returned. The questio ...

AngularJS enables you to easily manipulate image width and height using the ng-file-upload feature

Seeking assistance with validating image width and height based on a 1:3 ratio prior to uploading using ng-file-upload. The validation should occur before sending the image to the server. Unsure how to retrieve the dimensions of the selected image for val ...