The click event listener declared with v-on inside a Vue Component fails to trigger

I am currently working on a Vue instance for a sidebar within my application that displays a list of menu items. In order to achieve this, I have created a local component with the following template structure:

template:'<div><li class="custom-erp-menu-list" v-on:click="toggleOpenChild">'+
    '<a href="#">'+
        '<span>'+
            '<img src="assets/images/dollar-bills.svg" class="custom-erp-module-list-icon custom-erp-user-icons" width="18" height="18" alt="">'+
        '</span>'+
        '<span class="custom-erp-menu-parent">Purchase Order</span>'+
    '</a>'+
    '<ul class="nav custom-erp-menu-child-dropdown" id="purchase-order-child">'+
        '<li><a href="page-profile.html" class="custom-erp-menu-child">Profile</a></li>'+
        '<li><a href="page-login.html" class="custom-erp-menu-child">Login</a></li>'+
        '<li><a href="page-lockscreen.html" class="custom-erp-menu-child">Lockscreen</a></li>'+
    '</ul>'+
'</li></div>'

An issue has arisen where an error message is displayed stating that:

property or method "toggleOpenChild" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property

If you'd like to see a demonstration and explore further, you can visit the DEMO here.

Answer №1

To properly implement the functionality of toggling open child elements in your component, make sure to place your toggleOpenChild method within your component's methods section. See the example code below:

components: {
  "side-bar-modules": {
    template:
      '<div><li class="custom-erp-menu-list" v-on:click="toggleOpenChild">' +
      '<a href="#">' +
      "<span>" +
      '<img src="assets/images/dollar-bills.svg" class="custom-erp-module-list-icon custom-erp-user-icons" width="18" height="18" alt="">' +
      "</span>" +
      '<span class="custom-erp-menu-parent">Purchase Order</span>' +
      "</a>" +
      '<ul class="nav custom-erp-menu-child-dropdown" id="purchase-order-child">' +
      '<li><a href="page-profile.html" class="custom-erp-menu-child">Profile</a></li>' +
      '<li><a href="page-login.html" class="custom-erp-menu-child">Login</a></li>' +
      '<li><a href="page-lockscreen.html" class="custom-erp-menu-child">Lockscreen</a></li>' +
      "</ul>" +
      "</li></div>",
    data: function() {
      return {
        user: []
      };
    },
    methods: {
      toggleOpenChild: function(event) {
        var currentParent = $(event.currentTarget)
          .find(".custom-erp-menu-parent")
          .text();
        var childListID = currentParent.toLowerCase().replace(/ /g, "-");
        $(".custom-erp-menu-list > ul")
          .not($("#" + childListID + "-child"))
          .slideUp()
          .removeClass("custom-erp-menu-child-open");
        if ($("#" + childListID + "-child").is(":hidden")) {
          $("#" + childListID + "-child")
            .slideDown(300)
            .toggleClass("custom-erp-menu-child-open");
        } else {
          $("#" + childListID + "-child")
            .slideUp(300)
            .toggleClass("custom-erp-menu-child-open");
        }
      }
    }
  }
}

For a working example, check out this updated fiddle:

https://jsfiddle.net/cgxnLajf/1/

Answer №2

The function toggleOpenChild is located in the parent wrapper, but you are trying to call it in the child component where it is not defined.

Depending on your structure, you have two options: either move the method into the child component or make use of Vue events to handle this issue.


{
  template:
    '<div><li class="custom-erp-menu-list" v-on:click="toggleOpenChild">' +
    '<a href="#">' +
    "<span>" +
    '<img src="" class="custom-erp-module-list-icon custom-erp-user-icons" width="18" height="18" alt="">' +
    "</span>" +
    '<span class="custom-erp-menu-parent">Purchase Order</span>' +
    "</a>" +
    '<ul class="nav custom-erp-menu-child-dropdown" id="purchase-order-child">' +
    '<li><a href="page-profile.html" class="custom-erp-menu-child">Profile</a></li>' +
    '<li><a href="page-login.html" class="custom-erp-menu-child">Login</a></li>' +
    '<li><a href="page-lockscreen.html" class="custom-erp-menu-child">Lockscreen</a></li>' +
    "</ul>" +
    "</li></div>",
  data: function() {
    return {
      user: []
    };
  },
  methods : {

    // This method needs to be within the component
    toggleOpenChild : function()
    {
      console.log('open child');
    }
  }
}

View a demo similar to yours here: https://codepen.io/anon/pen/ePrOqm

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

Is it possible to include more than one ng-app directive on a single HTML page in AngularJS?

When working with Angular JS, I've noticed that I only get the desired output if I remove either the ng-app directive for demo1 or the models. It seems like having two ng-app directives active at the same time causes issues. As a beginner in Angular J ...

Is there an effective way to merge two collections?

I came across an issue where I am attempting to merge two arrays that resemble the ones listed below: var participants = [ {id: 1, name: "abe"}, {id:2, name:"joe"} ]; var results = [ ...

ajax call triggering knockout foreach update

Within my ViewModel, I have defined a variable called self = this; Another foreach binding is working in my code, but it is not within an ajax request. The initial UI load is functioning correctly. I have confirmed that self.wikiData is being updated by ...

Using AngularJS to dynamically load content into Owl Carousel 2

I'm having trouble loading the owl carousel in angularjs dynamic content. Here is the modified html code I am using: <div id="Galeria" owlcarousel class="youplay-carousel gallery-popup"> <a class="angled-img" href="http://www.youtube. ...

The React application is unable to communicate with my Express application in a production environment, despite functioning properly during development

Currently, I am attempting to make a basic get request to my express backend located at mywebsite.com/test. The expected response from the server should be {"test": "test"}. While this is working perfectly fine in development on localho ...

An easy guide to using validators to update the border color of form control names in Angular

I'm working on a form control and attempting to change the color when the field is invalid. I've experimented with various methods, but haven't had success so far. Here's what I've tried: <input formControlName="pe ...

The cookie is not displaying in the web browser

Why are my cookies not showing in the browser? I have tried multiple times, but even though the backend is sending the cookie, it is not being stored in the browser. I have also attempted to use different browsers like Chrome and Microsoft Bing. In Postma ...

Exploring the power of computed properties and composables in Vue 3.2 through the setup script tag

Exploring the latest features of Vue (version 3.2) has been quite exciting for me. I recently developed a useFetch composable to leverage reusability based on the vue documentation. useFetch.js import { ref } from 'vue' import axios from ' ...

Modify Chartjs label color onClick while retaining hover functionality

Currently, I have implemented vue-chart-js along with the labels plugin for a donut chart. Everything is working well so far - when I click on a section of the donut chart, the background color changes as expected. However, I now want to also change the fo ...

What is the best way to filter out specific data fields from console.log in JavaScript?

When working with Java, I often use lombok to exclude certain fields from being printed. For instance, the @ToString.Exclude annotation can be used to prevent printing the user token. import lombok.ToString; public class TokenResponse { @ToString.Excl ...

Code containing insertAdjacentHTML() does not run as expected due to injection of script

I have a scenario in my application where I am sending a request from the client to a node.js server. The server responds with an HTML containing a script: app.post('/verify', cors(issue2options), async (req, res) => { let auth = await mon ...

Using JavaScript to open links in a new tab with the target

document.getElementById("mahacareer").onclick = function () { window.open("http://www.mahacareermitra.in", '_blank'); }; <a href="" id="mahacareer">Access the portal</a> Hi there, I am looking to have the link above open in a new tab ...

Unable to showcase array JSON values on HTML using ng-model

Utilizing ngTagInput for autocomplete textbox and successfully receiving suggestions. To display the values of data-ng-model (named "list") I am using: {{list}} and it is showing correctly. However, when selecting "list1", the display appears as: [{"lis ...

Modify the date format inside the content of an HTML element or its descendants (excluding their attributes)

I have been trying to reformat some dates using JavaScript. My initial approach was: var regex = /(\d{4})-(\d{2})-(\d{2})/g; $('.container td').each(function() { $(this).html($(this).html().replace(regex, '$3-$2-$1')); ...

Trouble with setting up custom static route

Greetings! I am currently working on setting up my project in React and here is my current project structure: -public --w ---dist ----bundle.js ---index.html -server --server.js -src --app.js -webpack.config.js -package.json -.babelrc For my server, I am ...

Utilizing external JSON data in JavaScript for retrieval

Is there a way to retrieve the value of categories.name_category in JavaScript? The AJAX call to the REST API is functioning correctly: https://i.sstatic.net/WJzoL.png I attempted to access it like this, but unfortunately it did not work as expected: ht ...

What is the method to select a hyperlink that includes a variable in the "href" attribute and click on it?

Currently, I am in the process of creating acceptance tests utilizing Selenium and WebdriverIO. However, I have encountered a problem where I am unable to successfully click on a specific link. client.click('a[href=#admin/'+ transactionId + &apo ...

Having trouble compiling jsx with gulp, webpack, and the babel-loader combination

UPDATE: vue-tables-2 has been updated to now come pre-compiled, eliminating the need for loaders. When using the templates option, it is recommended to utilize scoped slots, which do not require any special configurations. I am currently utilizing gulp, w ...

Ways to effectively test a custom hook event using Enzyme and Jest: A guide on testing the useKeyPress hook

Looking for guidance on testing a custom hook event called useKeyPress with Enzyme and Jest This is my current custom hook for capturing keyboard events and updating keyPress value: import React, { useEffect, useState } from 'react' const useKe ...

Maximum Age Setting for Iron Session Cookie

Currently, I am attempting to configure a Next JS application with iron-session and a 'remember me' feature. The objective is for the maxAge of the iron-session cookie to be extended to a week if the user selects the remember me option on the log ...