Switch between various components using Vue

Hello, I am currently diving into the world of VueJS and eager to learn more about it.

I recently created a simple tooltip that should appear when clicked and disappear when clicked again. I managed to achieve this with basic beginner-friendly code for a single tooltip.

<div v-if="toolTipContent.length > 0" class="c-tooltip">
      <a @click="(clicked) ? clicked = false : clicked = true" class="c-tooltip--link">
          {{ $label('toolTipLink') }}
      </a>
      <div v-html="toolTipContent" v-if="clicked" class="c-tooltip--content"></div>
</div>

As I progress, I now want to implement multiple tooltips. Simply copying the existing code and making changes doesn't seem like an optimal solution.

So, I am experimenting with something like this:

<div v-if="toolTipContent.length > 0" class="c-tooltip">
  <a @click="toggleEl" class="c-tooltip--link">
    {{ $label('toolTipLink') }}
  </a>
  <div v-html="toolTipContent" v-show="clicked" class="c-tooltip--content"></div>
</div>

and in JS, I added the following method:

methods: {
    toggleEl(e) {
      e.target.nextSibling.classList.toggle("show");
    }
  },

However, I feel a bit stuck at this point. Although I can toggle a class on the next sibling element (as shown above), it feels like a jQuery approach in Vue. I believe there must be a more Vue-native way to handle this using the clicked value, but currently, all tooltips are either shown or hidden together. Additionally, I am using v-show but feel that v-if might be a better alternative. The challenge is that with v-if, I can't target the content since it's not part of the DOM.

I would appreciate any guidance on the recommended approach to tackle this issue effectively.

Answer №1

To efficiently manage all your tooltips and their properties (such as clicked status and content), a recommended approach is to store them within the data() section of your Vue application.

<script>
...
data() {
  tooltips: [
    {
      content: content1,
      isClicked: false
    },
    {
      content: content2,
      isClicked: false
    }
  ]
},
...
</script>

Subsequently, you can effortlessly display these tooltips in the template section.

<div v-for="tooltip in tooltips" v-if="tooltip.content > 0" class="c-tooltip">
      <a @click="clickTooltip(tooltip)" class="c-tooltip--link">
          {{ $label('toolTipLink') }}
      </a>
      <div v-if="tooltip.clicked" class="c-tooltip--content">{{tooltip.content}}</div>
</div>

Note the dynamic utilization of tooltip as the 'current element' above.

Finally, it's crucial to handle the clickTooltip function responsible for handling clicks. For better organization and clarity, it's advisable to define this function as a separate method within the script section:

<script>
...
methods: {
  clickTooltip(tooltip) {
    tooltip = !tooltip
  } 
}
...
</script>

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

How to extract a subset of data from an existing object and create a new object in Vue JS

My latest project involves creating a search app to find products. I have implemented a PHP script that returns results in JSON format when a keyword is submitted. The data retrieval is done using axios. The challenge I am facing is with handling the disp ...

transfer properties to a dynamic sub element

I am currently working on a multi-step form project. I have successfully implemented the form so that each step displays the corresponding form dynamically. However, I am facing challenges in passing props to these components in order to preserve the state ...

Tips for creating a mobile-friendly 30-day chart with chart.js

I created a chart displaying 30 days of absence data using the react-chartjs-2 library, but it is not responsive. How can I make it responsive? Here's how it appears on a laptop: chart on laptop And this is how it looks on mobile: chart on mobile T ...

The criteria set by jQuery are met

I have developed my own custom form validation for two inputs: one for a phone number and the other for an email address. Additionally, I have integrated two forms on a single page. Here is a snippet of my code: var email, phone; if (email address passe ...

Unexpected JavaScript behavior triggers Safari's crash on iOS platforms

In my Sencha Touch application, I am implementing a feature where users can download 5000 records in JSON format and display them in an Ext.List control. The downloading of records works smoothly using JSON.parse() and storing the data locally. However, u ...

The PHP header() function is not properly redirecting the page, instead it is only displaying the HTML

After double checking that no client sided data was being sent beforehand and enabling error reporting, I am still encountering issues. The issue revolves around a basic login script with redirection upon validation. <?php include_once "database- ...

Ways to make the background color white in Bootstrap 5

Can someone assist me in changing the background color of my portfolio to white? I attempted to use global CSS, but the black background on both sides of the page is preventing the change. return ( <> <Navbar /> <main className= ...

Tips for recognizing when AJAX content, such as images and text, has been fully loaded within a div while utilizing both AJAX and jQuery

$.ajax({ type: 'POST', url: 'show-photo3.php', data: 'type='+type+'&count='+count+'&aid='+aid, dataType: 'html', success: function(response) { //alert(response ...

Tips for incorporating various color schemes into all sides of a shape generated through the extrude geometry feature in three.js

I have recently designed a wall-like structure using extrude geometry and now I want to assign different colors to each side based on the settings below: var extrusionSettings = { curveSegments:5, steps: 10, amount: 200, be ...

Refrain from showing content beneath a certain element

Is there a way to hide all content that appears after a specific element, such as a particular class of div? The issue I am facing involves using a 1&1 webpage builder with a restrictive layout-template enforced by my boss. I am trying to remove the foote ...

There was an error of "Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor"

I've been diving into cannon.js and encountering the following error: Uncaught TypeError: CANNON.NaiveBroadPhase is not a constructor. I've tried numerous solutions but none seem to be working. Here's a snippet of my script: var scene, came ...

Encountering a 'DiscordAPIError: Unknown interaction' error while attempting to share details about a command

As I work on a slash command to deliver information about a specific command when users type /help, I encountered an error when trying to add multiple commands: E:\v13\node_modules\discord.js\src\rest\RequestHandler.js:298 ...

SignalR error: A type conversion issue has occurred where it is not possible to directly convert a task returning an object to a string

I'm encountering an issue with my C# hub class where the JavaScript code is returning a System.Threading.Tasks.Task instead of a string. I need help modifying the JavaScript method to return an actual string. Below is the hub class: public String ge ...

Issue with React occurring when attempting to delete an input component

I seem to be facing a challenge that I can't quite figure out whether it's related to React or not. To help illustrate the issue, I've created a simple example outside of my project: https://codepen.io/as3script/pen/VMbNdz?editors=1111 Wit ...

Hover over a particular element using a loop in Vue.js

Is there a way to change the price button to an Add to Cart button on mouseover, considering the true false data trigger for each item? How can we specify which item to target when hovering over the price section? Below is the code snippet: template: < ...

Converting Repository Objects to Json in Symfony3

element, I am facing an issue while attempting to send a repository object as JSON. In my controller code, I have implemented a conditional check to ensure that the request is made via XmlHttpRequest. Upon receiving the data and fetching the corresponding ...

Create a variety of tables populated with numerous hyperlinks within each table on a webpage

I have a website where I need to display multiple tables with different data, along with appropriate links within the table cells. Plan: Each table on the webpage represents a different school subject, showcasing performance metrics such as SAT scores, fi ...

Change the behavior of an onclick event on the second click

I'm trying to make a button on my website that not only plays music when clicked but also changes the text inside the button to "Go to SoundCloud" and redirects to SoundCloud. Currently, I have been able to achieve both functions separately - redirect ...

The model fails to bind when JSON is sent to the MVC controller

I've been facing an issue with my JSON payload not getting binded in my controller. I attempted creating a class with List<Models.UpdateChatRequestModel> Chats, but that didn't work for me. I also tried using an array name, but that approac ...

"Did you come across `item()` as one of the methods within the array

While studying the book 'JavaScript and jQuery Interactive Front-End Web Development', I came across this interesting sentence: You can create an array using a different technique called an array constructor. This involves using the new keyword ...