Triggering events on multiple elements with Vue.js when clicked

I am currently working on a feature that involves hiding and showing descriptions of image thumbnails when clicked by the user. I tried following a VueJS tutorial on transitions, but unfortunately only one thumbnail is properly functioning while the rest are not. After some trial and error, I decided to remove the script. Let's consider a pseudo code example using jQuery:

<div id="app">
   <p> 1 </p>
   <p> 2 </p>
</div>

jQuery("#app p").click(function(){
      alert(p.text);
   });

We just need this script where alert(p.text) will display different values depending on which <p> element the user clicks on, without having to write separate scripts for each individual element.

I'm struggling with implementing a similar functionality in VueJS. In essence, I'm unsure how to apply one instance of VueJS with a click event to multiple elements at once.

Answer №1

Would you like it such as this?

var X = new Vue({
  el:"#app",
  data:{
    items:[
      {name:'Example1',desc:'example1 Description',display:false},
      {name:'Example2',desc:'example2 Description',display:false},
      {name:'Example3',desc:'example3 Description',display:false},
    ]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app">
   <div v-for="item in items">
    <span @click="item.display = !item.display">{{item.name}}</span>
    <span class="" v-if="item.display">: {{item.desc}}</span>
   </div>
</div>

Answer №2

<template>
  <div>
    <p v-for="element in items" @click="handleClick(element)">{{element}}</p>
  </div>
</template>

<script>
export default {
  data () {
    return {
      items:[1,2,3,4,5]
    }
  },
  methods:{
    handleClick:function(selectedItem){
      alert(selectedItem);
    }
  }
}
</script>

Exploring the distinctions between MVC and MVVM architectures.

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

Tips for retrieving multiple relationship data in my Laravel Vue project

I have three models: "User", "Review", "ReviewReply" In the User Model public function reviews() { return $this->hasMany('App\Models\Review'); } public function reviewReplys() { return $this-> ...

Does React trigger a re-render when setState is called even if the state value remains unchanged?

Imagine I create a React component with an initial state of {random: 1}. Now, if I were to execute the following code: this.setState({random: 1}) Would this action result in triggering a re-render of the component? Furthermore, is there a method to avoid ...

How can I hide a root layout component in specific nested routes within the app directory of Next.js?

Is there a way to prevent rootlayout from being wrapped around dashboardlayout? Explore the latest documentation for Next.js version v13: https://i.sstatic.net/M0G1W.png Take a look at my file structure: https://i.sstatic.net/nVsUX.png I considered usi ...

Opening a modal in React Material UI from an autocomplete component results in losing focus

My current challenge involves utilizing the material-ui library to create an autocomplete feature where each item is clickable and opens a modal window. The basic structure looks like this: const ModalBtn = () => { ... return ( <> ...

Refreshing the parent page in Oracle Apex upon closing the child window.When the child window

I have created an interactive report with a form where the interactive report is on page 2 as the parent page and the form page is on page 3 as the child page. In the parent page, I have written JavaScript to open a modal window (form page - page 3) using ...

Unlocking the AngularJS variable within the template script

My controller code: $scope.totals = totals; In the template, I am able to successfully inject HTML using this code: {{totals}} However, my goal is to access the totals variable in a script within the template. Here's what I attempted: <script& ...

Obtain every possible sequence of US phone number segments for a provided number

The format of a US phone number is as follows: (XXX) XXX-XXXX Given a string consisting only of digits with a length between 0 and 10, I want to generate an array of all possible chunks that match the US phone number format. For example: Input: "54" Out ...

Removing text that was added via the chart renderer in Highcharts can be accomplished by identifying the specific element

Instead of using a legend in my graph, I have added labels directly to the series (view example here). After drawing the graph with these labels attached, the user can click a button to add another series which hides some existing lines successfully. Howev ...

Ways to style a div element in CSS to achieve a unique shape

Hello there! I'm looking to achieve a tilted background div effect. Anyone have any tips or ideas on how I can do this? I'm new to web development and would appreciate the guidance. https://i.stack.imgur.com/wyj1X.png ...

"An error has occurred: ENOENT - The specified file or directory does not exist, cannot create directory" on the live website

I am facing an issue on my website where I need to create a folder and save some files in it. While the code works perfectly fine locally, once deployed on render, I encounter the following error: Error: ENOENT: no such file or directory, mkdir '/opt/ ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

What steps should I take to ensure that clicking this button triggers the API request and returns the data in JSON format?

I'm attempting to have the button with id 'testp' return an api request in json format, however it seems to not be functioning properly. You can find the HTML code link here: https://github.com/atullu1234/REST-API-Developer-1/blob/main/js-bu ...

effective method for iterating through JSON data using JavaScript or jQuery

Upon receiving a JSON object from the server, it looks like this: { "0": { "id": "1252380", "text": "This whole #BundyRanch thing stinks to high hell. Can it be a coincidence that Harry Reid n his son have a financial interest in this land?", ...

Creating a responsive gallery using CSS techniques

I'm currently working on creating a simple gallery. My goal is to achieve the following design: https://i.sstatic.net/jq8pe.jpg However, the result I'm getting looks like this: https://i.sstatic.net/hSZyj.png The issue I'm facing is that ...

I am looking to use flexbox and Vue.js to organize my sent messages in blue on the right and received messages in yellow on the left. How can I achieve this grouping effectively?

I've successfully built a messenger system using Vue.js with a Laravel backend. My goal is to display messages from myself (Jim, the logged in user) on the right side in blue and messages from Debbie (the recipient) on the left side in yellow, similar ...

How to extract value from the URL in NextJS

I am attempting to pass a value through the URL and then extract that value in search.js using a router. However, I keep encountering this error: TypeError: Cannot read properties of undefined (reading 'q') <form onSubmit={handleSubmit}&g ...

Steps to assign a value to an input element using the state in a React application

Hey there, I hope everything is going well for you! I have a question regarding setting the value of an input field based on the state received from props. I've tried to populate the input with data from the "profile" state using placeholders, but it ...

Attempting to grasp the intricacies of HTML5/JS video playback quality

I've been diving deep into research on this topic, but I can't seem to find a straightforward answer to my specific query. My main focus is understanding the inner workings of how video players transition between different quality settings (480p, ...

React's createRef() versus callback refs: Which one provides the ultimate edge in performance?

Lately, I've delved into React and grasped the concept of refs for accessing DOM nodes. The React documentation discusses two methods of creating Refs. Could you elaborate on when a callback ref is preferable to createRef()? Personally, I find createR ...

Manually update the DOM rather than depending on React's reconciliation process

Creating a React component that wraps a complex rendering API is my current goal. This specific API has the ability to render a plot into HTML+SVG and also offers functionality to update the plot with new data efficiently. I am keen on utilizing this updat ...