Conceal div when clicked in Vue.js

Could you provide the Vue.js equivalent for this jQuery code snippet?

$('.btn').click(function(){  $('.hideMe').hide()  });

Answer №1

Out of the box, jQuery is good to go, but Vue.js requires a bit more setup. To start using a Vue.js component or App, you need to bind that component with its data to a specific HTML tag within your template.

For instance, in this scenario, the specified element is

<div id="app"></div>
and is accessed through el: #app, reminiscent of jQuery syntax.

Once you define a variable like isHidden which represents the toggle state (initialized as false inside the data object), you'll then use Vue-specific code such as v-on:click="" and v-if="".

To dive deeper into Vue.js coding techniques, it's recommended to consult the official documentation:

Note: Delve into the comprehensive documentation for a thorough understanding of Vue.js concepts.

var app = new Vue({
  el: '#app',
  data: {
    isHidden: false
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582e2d3d186a766d76696b">[email protected]</a>/dist/vue.js"></script>

<div id="app">
  <button v-on:click="isHidden = true">Hide the text below</button>
  <button v-on:click="isHidden = !isHidden">Toggle hide and show</button>
  
  <h1 v-if="!isHidden">Click to hide me!</h1>
</div>

Answer №2

If you're new to Vue, this question might seem basic at first. I recommend checking out the guide for a quick answer to your query.

But if you're still in need of an answer, here's how you can toggle elements in Vue:

new Vue({
 el: '#app',
 data () {
   return {
     visibility: true
   }
 },
})
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id="app">
  <button @click='visibility = !visibility'> Click Here </button>
  <div v-show='visibility'>Showing Content</div>
</div>

Answer №3

<div>
    <div>

        <button v-on:click="isHidden = !isHidden">Click here to toggle hide and show</button>

        <h1 v-if="!isHidden">Hide me when button is clicked!</h1>
    </div>
</div>

name: "Modal",
    data () {
        return {
            isHidden: false
        }
    }

Answer №4

When attempting to achieve this task, I found that using a dynamic array instead of a single Div required more than just a static Vue variable.

@samayo points out that the hide action from jQuery vs Vue is not different, so an alternative method is to trigger the jQuery through the @click function.

The Vue Dev kit advises against mixing JS inline with @click events, and running into issues like @user9046370 did when trying to incorporate the jQuery command within @click.

Here's a new way to approach this:

<tr v-for="Obj1,index in Array1">
    <td >{{index}}</td>
    <td >
        <a @click="ToggleDiv('THEDiv-'+index)">Show/Hide List</a><BR>
        <div style='display:none;' :id="'THEDiv-'+index" >
            <ul><li v-for="Obj2 in Array2">{{Obj2}}</li></ul>
        </div>
    </td>
</tr>
Method:
ToggleDiv: function(txtDivID)
{
    $("#"+txtDivID).toggle(400);
},

This method also allows for incorporating fancy jQuery transitions if desired.

Answer №5

<template>
    <button class="btn btn-outline-secondary" type="button"><i class="fas fa-filter" @click="toggleFilter"></i></button>
</template>

<script>
    export default {
        data: () => ({
            filterActive: true,
        }),

        methods: {
            showFilter() {
                eventHub.$emit('show-guest-advanced-filter');
                this.filterActive = false;
            },

            hideFilter() {
                eventHub.$emit('hide-guest-advanced-filter');
                this.filterActive = true;
            },

            toggleFilter() {
                return this.filterActive ? this.showFilter() : this.hideFilter();
            }
        }
    }

</script>

This method is effective.

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

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Repeat the execution or refresh an EventListener

I am a beginner in the world of coding, currently working on my inaugural project to create a web-based game using HTML, CSS, and JavaScript. I have encountered an issue with the .addEventListener() method that I couldn't seem to find a solution for ( ...

When using Next.js revalidate, an error may occur stating: "There are keys that require relocation: revalidate

I have been attempting to utilize the revalidate function in my code by following the example provided by Vercel. However, I keep encountering an error. Here is the snippet of code that I am currently using: export async function getServerSideProps() { c ...

Encountered an issue while building npm: "Error: Unable to locate module @restart/context

Lately, I've encountered an issue with npm build after upgrading to the latest version of react-bootstrap (1.0.0-beta.6). While creating an optimized production build... Failed to compile. Module not found: '@restart/context/forwardRef'. P ...

Unlocking Authorization in VueJS

Currently, I have Laravel 5.4 integrated with Vue.js 2.0. Is there a way to utilize Auth::user() within a VueJS template? Here's an example... <template> <p>{{ Auth::user()->name }}</p> </template> export default {} ...

Tips for incorporating external JavaScript code into React components

I have been tasked with integrating a graphical widget into a React component for a project I am working on. The widget_api code provided by RIPE Stat is required to accomplish this. Previously, in HTML5, the integration was successful using the following ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

Using VueJs to associate boolean values with dropdowns

I am currently working on a form with a dropdown menu containing two options: "True" and "False". My goal is to save the selected value as a boolean in the form. For instance, when the user selects "True", I want the value stored as true in boolean format ...

Tips for retrieving a reactive variable from a setup() method?

I'm currently working on a small notes app and using Vue3 + Typescript to enhance my skills. The following code snippet demonstrates how to dynamically create and display an Array of notes: <template> <q-layout> <div v-for ...

Opt for router-link over web route when working with Laravel

While working with Laravel 9 and Vue 3, I encountered a peculiar issue. When navigating to a link by clicking on the menu, everything worked as expected. However, if I tried to access the same link by directly typing the URL or refreshing the page, I would ...

Scroll to top on page load in Vue

I've integrated Gridsome into my portfolio website. However, I've encountered an issue where on mobile or tablet devices with longer pages, Firefox fails to scroll back to the top when navigating. Interestingly, this problem doesn't occur in ...

Is there a way to customize the Master Page in asp.net to resolve the Bootstrap4 dropdown issue? I am encountering an error message that says "Uncaught TypeError: Bootstrap

Hello everyone, I recently encountered an issue while trying to use dropdown in my project after updating to bootstrap 4. It was working perfectly fine before the update, but now I'm getting an error in the JavaScript. The error that pops up when I tr ...

Detonating the second-level element in a PHP/Typescript array

My PHP code is currently formatting an array for me with the following structure: $data = $dataQuery->fetchAll(PDO::FETCH_ASSOC); if(count($data)){ $data_arr=array(); $data_arr["records"]=array(); $data_arr["records"] = ...

Creating a tooltip for new list items: A step-by-step guide

I'm currently working on creating a tooltip using JQuery for incoming list items. Users will input text in a textfield, press enter, and those values will be displayed in a visible list on the website. I intend to have a tooltip associated with each i ...

Saving search results using AJAX in Vue and Laravel's database

I am working towards creating a feature with two input fields where users can type in the three-letter code of an airport. Through AJAX, a query will run to verify if the airport exists in the database. If it does, the name of the airport will be displayed ...

The Angular service/value is failing to retrieve the updated variable from the $(document).ready() function

Currently, I'm facing an issue with my Angular service/value. It seems to be grabbing the original variable instead of the new one that is supposed to be inside $(document).ready(). Here's the relevant code snippet: var app = angular.module("app ...

"Exploring the process of adding external JavaScript or CSS files into Angular 2 using webpack

Embarking on an angular 2 project with webpack has been quite the adventure. Utilizing the angular2-webpack-starter from https://github.com/AngularClass/angular2-webpack-starter. The task at hand is to integrate external javascripts and css into my app. D ...

Utilize a CSS selector to target all deleted nodes using the MutationObserver in the HTML5 API

Is there a way to retrieve all removed nodes from the DOM that have specific classes using CSS selectors? Below is an example of how it can be done with some complexity, but is there a simpler and more general approach? new MutationObserver(mut =& ...

Generating a download link with an expiration feature in node.js or express for both frontend and backend operations

Hello everyone, I'm a beginner here and have recently started working with node.js and express.js. I am looking to implement a download link on my website that expires after a certain time, but I've been struggling with the code for about a week ...

JavaScript if statement can be used to evaluate two variables that have the same values

I am currently working on a Wordle-style game with a 6x6 grid. I'm sending the row as an array through a socket, and while I can check if a letter is correct, I'm having trouble with identifying duplicates that are in the wrong position. I iterat ...