Issue with Vue 2 emitting events and not properly executing associated method, despite correct setup

I am attempting to trigger an event from a child Vue component to its parent using this.$emit('collapsemenu').

However, when I try to capture this event in the parent using

v-on:collapsemenu="collapseMenuf($event)"
, nothing seems to happen. The method does not execute, despite the child emitting the event.

Is there something crucial that I am overlooking here? I have searched for similar issues online, but none of the solutions have worked so far.

Navbar (Child)

<template>
  <div class="navbar">
    <div class="navbar-left">
      <svg
        @click="collapse_menu"
        xmlns="http://www.w3.org/2000/svg"
        class="hamburger"
        viewBox="0 0 20 20"
        fill="currentColor"
      >
        <path
          fill-rule="evenodd"
          d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z"
          clip-rule="evenodd"
        />
      </svg>
    </div>
    <div class="navbar-right"></div>
  </div>
</template>

<script>
export default {
  name: "Navbars",
  components: {},
  methods: {
    collapse_menu() {
      console.log("clicked");
      this.$emit("collapsemenu", "TRUE");
    },
  },
};
</script>

<style lang="scss" scoped>
.navbar {
  width: 100%;
  height: 70px;
  background: yellow;
  padding: 10px;

  &-left {
    width: 50%;
  }
}

.hamburger {
  cursor: pointer;
  height: 30px;
}
</style>

Main

<template>
  <div class="dashboard h-screen bg-red-200">
    <Menu class="menu"></Menu>

    <div class="content">
      <Navbar v-on:collapsemenu="collapseMenuf($event)"></Navbar>
    </div>
    <!-- <Content></Content> -->
  </div>
</template>

<script>
import Navbar from "../../components/dashboard/navbar.vue";
import Menu from "../../components/dashboard/menu.vue";
export default {
  name: "Dash-main",
  components: { Navbar, Menu },
  data() {
    return {
      collapse: false,
    };
  },
  methods: {
    collapseMenuf(value) {
      console.log("fsd");
      this.collapse = value;
      console.log(value);
    },
  },
};
</script>

<style lang="scss" scoped>
.dashboard {
  display: flex;
  width: 100%;
}

.content {
  width: 100%;
}
</style>

Answer №1

If you want to implement this from the parent component, follow these steps:

  <Navbar v-on:collapsemenu="collapseMenuf"></Navbar>

For the child component:

<svg
    @click="collapse_menu($event)"
    xmlns="http://www.w3.org/2000/svg"
    class="hamburger"
    viewBox="0 0 20 20"
    fill="currentColor"
  >

To access the $event within a function, use the following code snippet:

const collapse_menu = (e) => {
  console.log(e);
  emit('click', e.target);
};

If you need more information on vue emits, refer to this link

Answer №2

This particular issue has been a bit perplexing for me as well. I encountered the same problem and even though the documentation of Vue.js v2 indicated that the following code snippets should work:

// on child component
this.$emit('event-name')
// on parent template
<child-component-name v-on:event-name="parent-method"></child-component-name>

Unfortunately, it didn't work for me either. However, I managed to solve the problem by implementing the following approach instead:

// on child component
this.$root.$emit('saveSettings', this.apiRequestSetupObj);
// in parent component add this on mount
const thisInstance = this
this.$on('saveSettings', function (data) {
         thisInstance.saveSettings(data);
});

I suggest giving this alternative method a try.

It's worth noting that if you're interested in understanding the distinction between using this.$emit versus this.$root.$emit in Vue.js, you can refer to this informative discussion: this.$emit vs. this.$root.$emit, best practice in Vue.js

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

Utilizing window.location.pathname in Next.js for precise targeting

Are you familiar with targeting window.location.pathname in NEXT.JS? I encountered a red error while using this code in Next.js const path = window.location.pathname console.log(path) // I am able to retrieve the pathname here Then { ...

Utilizing Regex Patterns to Manipulate CSS Attributes

I am dealing with a string containing CSS properties and their values: str = "filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000'); background: -webkit-linear-gradient(top, black, wh ...

Unable to transmit an object containing a property that includes an array of other objects

I am attempting to send an object that has the following structure: var postBody = { id: userID, objectID: [0, 1], objects: [ {id: 0, x: 0.33930041152263374, y: 0.08145246913580247, width: 0.0823045267489712, height: 0. ...

Switching from constructors to Hooks in REACT

I am currently working on adding a modal example within a function in my project. I have a specific requirement to incorporate hooks instead of using the constructor in a class-based component. This is the code snippet with the class-based implementation: ...

Is it necessary to remove a Javascript Event Listener before a VueJS element is unmounted?

I have a straightforward vuejs directive that attaches an event listener to the DOM element upon its mounting. I'm questioning whether it's necessary to detach this event listener before the element is unmounted later on. Despite the fact that th ...

How can I implement a Dynamic Input field using Angular?

Suppose there is an input field where a user enters an ID. Once the user clicks the "add" button, I need to send a request to my server to fetch a "name". Afterwards, I want to disable the text input field, hide the "add" button, and show a number input fi ...

Activating view loading in AngularJS through child window authentication (OAuth)

I have tried implementing OAuth in AngularJS using Hello.js following what I believe is the best practice. However, I am encountering some issues with my current approach as described below: After injecting Hello.js into Angular and setting up the OAuth p ...

Retrieving the attributes of a JSON object based on their names

I'm currently working on storing video information using JSON. I've managed to successfully read the JSON file, but I'm facing some challenges when trying to access the properties of the object. Specifically, I'm struggling with accessi ...

Maximizing JavaScript DOM efficiency

In my code, I have numerous elements that need to be hidden and displayed dynamically. To facilitate this, I plan on utilizing the document.getElementById('x').style.display method. However, instead of directly using this method each time, I have ...

Is there a way for me to retrieve a variable from a $.getJSON function?

How can I access the StudentId variable outside of the $.getJSON() function? j.getJSON(url, data, function(result) { var studentId = result.Something; }); //need to use studentId here I suspect this issue is related to scopes and differs from how it ...

Exploring the Functionality of ngMousedown and ngMouseup in AngularJS

Is it viable to apply ngMousedown to add a class to a div, and then use ngMouseup to remove the class once more? Currently, I am utilizing ng-mousedown="activateClass()". Within the activateClass() function, I modify $scope.className="data-active", which i ...

Restrict the input to only allow for parentheses, disallowing any letters or numerical characters

Only parentheses are allowed in the input field; letters and numbers will not be accepted. function checkBrackets() { var inputVal = document.getElementById("input").value; var result = document.getElementById("strong").value; console.log(inputVal, ...

Save room for text that shows up on its own

I am currently dealing with a situation where text appears conditionally and when it does, it causes the rest of the page to be pushed down. Does anyone know the best way to reserve the space for this text even when it's not visible so that I can pre ...

Retrieve the URL of the previously visited webpage using Javascript

Is there a way to retrieve the URL of the last visited page using JavaScript? I want to be able to track which product the user viewed most recently. I have attempted the following code: var x = document.referrer; document.getElementById("demo").innerHTML ...

I would like to have text show up instead of an alert when validation is triggered

Hey there, I need some help with JavaScript as I'm just getting started. Basically, I want to display the text "please fill in" next to a textbox if the user hasn't entered any information. <!DOCTYPE html> <head> <title>Easy ...

Steps for generating random numbers from a set of given numbers

I am faced with a scenario where I need to generate random numbers based on a given set of numbers. For instance, if I have an array num=[23,56,12,22], I would like to obtain a random number from this array. ...

Using Node.js, express, jade, highcharts, and a 2D array

Greetings, I am relatively new to the realm of javascript/node.js/express/jade/highcharts etc... The predicament at hand is as follows: I have a template that takes in a few parameters which are pre-processed in my router code. These parameters are group ...

Iterate through the elements in an array in order to generate new elements

Currently, I am in the process of comparing various popular javascript frameworks and I need to generate an HTML element for each object retrieved from an API. const frameworks = [ { name: "angular" }, { name: "ember" }, { name: "rea ...

Issue: Module 'C:viteinvite.js' not found while setting up vue.js in Laravel project

Decided to dive into learning Laravel and Vue.js, so I followed a tutorial for installation found here: https://youtu.be/WLQDpY7lOLg?t=1058 Everything was going smoothly until I reached the npm run dev command... Below are the commands I executed in the ...

Reload the Angular application and navigate to a different state

Introduction In my extensive angular application, there are numerous forms for various items. These forms are associated with action objects that have unique schemaforms. The dropdowns in these forms vary based on the specific action and its parent comp ...