Implementing a toggle function in Vue.js to add or remove a class from the body element when a

I'd like to add a toggleable class to either the body element or the root element("#app") when the button inside the header component is clicked.

Header.vue :

<template lang="html">
 <header>
  <button class="navbar-toggler navbar-toggler align-self-center" type="button" @click="collapedSidebar">
  <span class="mdi mdi-menu"></span>
  </button>
 </header>
</template>

<script>
export default {
  name: 'app-header',
  data: {
    isActive: false
  },
  methods: {
    collapedSidebar() {

    }
  }
}
</script>

App.vue :

<template lang="html">
  <div id="app" :class="{ active: isActive }">
   ...
  </div>
</template>

! If I'm making any mistakes, please feel free to correct me. I'm still learning Vue.js :)

Answer №1

To trigger an event within your header and then potentially catch it in the mounted hook of your app component, follow this process:

Within your sidebar or another component:

on_button_click: function (){
    this.$emit('toggle_root_class');
}

In your app component:

mounted: function(){
    var _this = this;

    this.$on('toggle_root_class', function(){
             _this.active = !_this.active;
    });
}

It's important to note that Vue may limit the observation of events in sibling components. To address this, I recommend using an EventBus in my projects for easier event handling.

Answer №2

Your issue stems from the scope of your component. Attempting to retrieve data from Header.vue in App.vue is not feasible based on the structure outlined in your code. You may want to relocate the isActive data to App.vue or utilize Vuex as a solution.

Answer №3

If you want to toggle a class for an element that is not within the Vue template, consider using jQuery. One approach is to create a function that triggers when a button is clicked, allowing you to toggle a class on the body tag using jQuery.

<template lang="html">
 <header>
  <button class="navbar-toggler navbar-toggler align-self-center" type="button" :class="{ active: isActive }" @click="activeLink">
  <span class="mdi mdi-menu"></span>
  </button>
 </header>
</template>

<script>
export default {
  name: 'app-header',
  data() {
    return {
      isActive: false
    };
  },
  methods: {
    activeLink() {
         $('body').toggleClass('.class-name');
    }
  }
}
</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

Exploring Checkbox Limiting with jQuery

Is there a more efficient approach to restrict the selection of checkboxes? I want the script to be adaptable depending on the applied class, which will always indicate the maximum allowed value (e.g., "limit_1" or "limit_2"). Currently, I'm creatin ...

Identifying Changes with jQuery Event Listeners

I am trying to run some javascript code that is in the "onchange" attribute of an HTML element. For example: <input id="el" type="text" onchange="alert('test');" value="" /> Instead of using the onchange attribute, I want to trigger the e ...

Retrieve information from a JSON file according to the provided input

Can someone help me fetch data based on user input in JavaScript? When the input is 'Royal Python', I'm supposed to retrieve details about it. However, the code provided gives an error stating 'The file you asked for does not exist&apo ...

When placed in a conditional, the type of the body variable changes from a string to undefined

Unexpectedly, the final if block fails to retain the value of the body variable and transforms it into undefined. While the console log statement just before the block correctly displays the type of the variable as a "string", during the condition check an ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

What methods can I use to evaluate the efficiency of my website?

Is there a way to assess and improve website performance in terms of load time, render time, and overall efficiency? I've heard of YSLOW for firebug, but am curious if there are any other tools or websites available for this purpose. ...

Maximum number of days that can be selected with Bootstrap Datepicker

I currently have a datepicker set with the multidate option and I am looking to specify a maximum number of days that users can select, say 5 days. Once a user has selected 5 days, any additional days should become disabled dynamically. How can this be a ...

Having trouble saving text in a textbox?

Is there a way to store text in a text box for future use? Every time I reload the page, the text in the box disappears. I have attempted the following solution: <td align='left' bgcolor='#cfcfcf'><input type="text" name="tx ...

Are there any options available for customizing the animation settings on the UI-bootstrap's carousel feature?

If you're interested in seeing an example of the standard configuration, check out this link. It's surprising how scarce the documentation is for many of the features that the UIB team has developed... I'm curious if anyone here has experie ...

Loading tab content on click using jQuery

These tabs have a chrome-like appearance. When the first tab (Facebook) is clicked, it shows Facebook content. Clicking on the second tab (Twitter) displays the content of the first tab. Tabs three, four, and five show their respective contents without any ...

Discovering the Windows Identifier of the Opener Window in Chrome via JavaScript

I recently opened a link in a new window and realized that the current window's ID is now the ID of the newer window. I'm curious if there is any method to determine the window ID of the original window (the opener) from the perspective of the ne ...

Creating numerous strings using template literals

I am looking to create multiple strings using a template literal and an array variable. For instance, a template literal allows you to replace an expression with its content in a string: var = "world"; tpl = `Hello ${var}!`; console.log(tpl); // Hello wor ...

Maintaining the aspect ratio of images in Bootstrap Carousel: A complete guide

Using the default carousel from Bootstrap template has been working well for me. However, I've encountered an issue where resizing the browser window distorts the image aspect ratio by squishing it horizontally. I've tried various solutions to m ...

Error: Unable to access 'isCE' property of null - Custom Component Library

Struggling to create a custom component library for Vue 3 using ViteJS and NPM. Here is a breakdown of my setup, can someone guide me in the right direction as I have hit a roadblock for the past couple of days. Here's how my files are structured: d ...

Using JavaScript to control the state of a button: enable or

In the process of creating a basic HTML application to collect customer information and store it in a database, I have encountered a specific user interface challenge. Once the user logs into their profile, they should see three buttons. Button 1 = Print ...

I'm looking to center the column content vertically - any tips on how to do this using Bootstrap?

Hello! I am looking to vertically align the content of this column in the center. Here is an image of my form: https://i.stack.imgur.com/nzmdh.png Below is the corresponding code: <div class="row"> <div class="form-group col-lg-2"> ...

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Attempting to remove an attribute or property in JavaScript will not yield the desired result

When I try to close the menu after opening it, the inline style won't get removed despite trying different methods. The CSS only has text properties for alignment and the class can-transform contains a media query. That's all the information I h ...

Having trouble importing a module in my Node.js/Express application

I've encountered an issue while trying to import files into my node js server file. My usual method is correct in terms of paths, so I'm puzzled about what the error might be. import express from 'express' import mongoose from 'mon ...

Using jQuery to revert back to the original SRC after mouse is not hovering over an element

I've been working on a script to change the src attribute for an icon. The icon I'm loading is a different color and it's meant to notify the user about the link associated with it. Currently, I have the src changing to the second icon on h ...