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

Ensure that each child component receives a prop

Can you transfer a prop with a function to any child component? Specifically, I want to send a function from a parent component to each {children} element: <> <Navbar /> <main>{children}</main> <Footer /> </&g ...

Strange behavior in Angular's http response

When I make a call to my API and receive a JSON response, the code snippet below illustrates how I handle it: getAllLearn() { this.learnService.getAllLearn().subscribe(res =>{ // The console log shows that res.featured only has one index: ( ...

Strip away all HTML attributes within a string

I am in the process of developing an internal tool that allows a designer to input exported svg code into a text area and have the html code displayed in a syntax highlighter () When they paste their code like this <svg xmlns="http://www.w3.org/20 ...

Tips for displaying dynamic content in VueJS?

I'm currently working on an app that allows users to choose which type of vuetify element they want to display on the page. There are 4 options available for selection. My goal is to render the corresponding vuetify component when a user clicks on the ...

Transform the hue of symbols within D3-legend

I am attempting to modify the appearance of symbols in a legend. The variable below represents the available symbol types: var symbolTypes = { "triangleUp": d3.svg.symbol().type("triangle-up"), "circle": d3.svg.symbol().type("circle") }; I use this varia ...

Get the file that is attached for download

Is it possible to download attached files using Paperclip without relying on external libraries? I want to enable users to download the file immediately after uploading, before it reaches the backend. I managed to achieve this using file-saver But I&apo ...

Processing hover attributes in Tailwind-styled-components

I'm currently working on a website that features a dark mode, and I want to utilize the dark prop in tailwind-styled-components. The props work fine in all instances except for actions like hover, active, focus, etc. When attempting to use hover and t ...

What causes Angular to consistently redirect to the homepage?

Whenever I attempt to access the '/' route, it consistently displays the static-root-component (the main page component). However, if I try to access the '/welcome' route, it immediately redirects back to '/' and loads the sta ...

Vue.js 2: NPM Error! Installation failed for "@/config" directory due to issues

My system details are: $ nodejs --version v8.9.4 $ npm --version 5.6.0 I am attempting to integrate the https://github.com/wxs77577/adminify Vue.js/Vuetify template with the latest Laravel version. Here is what I have done so far: 1) Created a new L ...

The error message "The default exports (imported as 'Vue') could not be found in 'vue' while integrating Ruby on Rails with Vue. The webpacker setup was configured by running install:vue command

Take a look at the following code snippet from hello_vue.js file import Vue from 'vue' import App from '../app.vue' document.addEventListener('DOMContentLoaded', () => { const app = new Vue({ render: h => h(App) ...

Tips on detecting a collision between a cube mesh and the boundaries of a browser using ThreeJS

I'm a beginner in 3D games and ThreeJS. In the image above, my Mesh is located at the left boundary of the browser with a position of -1035 instead of 0. This leads me to question what exactly is the relationship between mesh.position.x in ThreeJS and ...

Comparison: Vue.js ref() vs. defineModel(). Unraveling the Distinctions

As a beginner in the world of Vue.js, I'm having trouble understanding the distinction between ref() and defineModel(). Tutorials on YouTube suggest that they facilitate communication between parent and child components. The following code snippet sho ...

The Model.function method is not a valid function that can be used within a router

Currently facing a challenge with my router setup. I have exported the function as shown in the code snippet below. This is the Model I am using: "use strict"; var mongoose = require('mongoose'); var bcrypt = require("bcryptjs"); var Schema = m ...

The CSRF token is mysteriously altering in places it should remain unchanged

Implementing the code below to prevent CSRF vulnerability if (!isset($_POST['_token'])) { $_SESSION['_token'] = bin2hex(random_bytes(20)); } I then use the token in hidden inputs named _token. In my main.js file, I include the foll ...

Can a Vuex action be called within a getter?

For instance, I utilize a Getter to create a logic for checking if an object has a specific content. const state = { object = [] } const getters = { CHECK_OBJECT_STATE: (state) => { if(Object.prototype.hasOwnProper ...

I am unable to utilize the map function as it results in a TypeError: The property 'map' is undefined and cannot be read

I recently delved into the world of "REACT" in order to work on the front-end of my own project. I encountered a problem for 2 days with the map function while getting data from my back-end and saving the IDs in the Cuartos array. I couldn't figure ou ...

How to access a method in main.js file from a .vue component

I'm working on a vue-cli project with one .vue file and main.js. I am trying to call a method from the .vue file in main.js, but I keep getting an error saying that the function is not defined. How can I successfully call a method inside the .vue file ...

Create an array that can contain a mix of nested arrays and objects

Working on my project using Angular and TypeScript includes defining an array that can contain arrays or objects. public arrangedFooterMenu: IMenuItemType[][] | IMenuItemType[] = []; typesOfData.forEach(type => { let filteredData: IMenuItemType | ...

What is the correct way to configure environment variables in a Next.js application deployed on Vercel?

As I develop my web app in Next.js, I have been conducting tests to ensure its functionality. Currently, my process involves pushing the code to GitHub and deploying the project on Vercel. Incorporating Google APIs dependencies required me to obtain a Cli ...

Does Objective C have a counterpart to the encode() method in JavaScript?

NSString *searchString = @"Lyngbø"; NSLog("%@",[searchString stringByAddingPercentEscapeUsingEncoding:NSUTF8StringEncoding]); The result is: Lyng%C3%B8 <script type="text/javascript"> document.write(escape("Lyngbø")); </script> The result ...