Unable to retrieve nested element from its parent

I am facing an issue with accessing a child element's method from the parent element using ref='menu'. When I try to call $refs.menu.show in a button element within the Vue app, it works fine. However, when I try to do the same in a photo element, it doesn't work. All components are registered in the parent Vue app.

//ERROR        
vue.js:634 [Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'show' of undefined"

    found in

    ---> <Photo>
           <Root>

Here is my HTML code inside #app:

    // For tests
    <button @click.prevent='$refs.menu.show'></button>

    <div class="center" :style="{ width : center_div_width+'px', height : window_height+'px'}">
        <template v-for='(row, index1) in info'>
            // Parent element
            <photo v-for="(item, index2) in row" :item="item" :art_width='art_width'>
                // Child element
                <cmenu ref='menu'>
                    <li>Test</li>
                    <li>Test2</li>
                </cmenu>
            </photo>
        </template>
    </div>
// JS

Components that I am using. I am attempting to call a nested app method from the template of the 'photo' component:

Vue.component('photo', {
    props: ['item', 'art_width'],
    template: `<a class='art' href="" :style="offset(item.offsetX, item.offsetY)" @mouseover="hover = true" @mouseout="hover = false">
                   <img v-bind:src="/media/ + item.path" class="img" :width="art_width+'px'">
                   <a href="" class='art-owner' align="center" v-show='hover'>{{item.owner}}</a>
                   <a href="" class='art-menu' align="center" v-show='hover' @click.prevent='$refs.menu.show'>...</a>
                   <slot></slot>
               </a>`,
    data: function () {
        return {
            hover: false,
        }
    },
    methods: {
        offset (valueX, valueY) {
          return `transform: translateX(${ valueX }) translateY(${ valueY })`
        },
    },

})
context_menu = Vue.component('cmenu', {
        template: `<div class='context-menu'>
                      <ul>
                        <slot></slot> 
                      </ul>
                   </div>`,
        data: function () {
            return {
                ifshow: false,
                style = null
            }
        },
        mounted() {
            window.addEventListener('click', (event) => {
                if (Object.is($el, event.target) == true) {
                    this.ifshow = false;
                }
            });
        },
        methods: {
            show: function(event) {
                this.ifshow = true;
            }
        }
    })

Answer №1

ref is a method used to create a reference to an element or a child component, which will be stored in the parent component's $refs object.

Each component, such as the photo component mentioned here, has its own scope and therefore its own set of $refs.

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

Incorporating Javascript .click() with Python Selenium Webdriver for Enhanced Script Functionality

Having trouble incorporating Javascript code into my Python Selenium script. The ".click()" method in Javascript is more efficient than Selenium. I need to translate this Javascript into Python, but I'm not familiar with JS : const MyVariable= $(&quo ...

Combining all elements of my application into a single HTML, JS, and CSS file

My AngularJS app has a specific structure that includes different directories for each component: theprojectroot |- src | |- app | | |- index.html | | |- index.js | | |- userhome | | | |- userhome.html | | | ...

Surprising automatic scrolling upon pressing the keydown button in Bootstrap

My webpage appears normal with the Bootstrap framework, but whenever I press the down key, the screen scrolls down and displays unexpected white space due to reaching the end of the background-image sized at 1798px * 1080px. Please refer to the image: He ...

Nested ng-repeats within ng-repeats

I have a question regarding the correct way to utilize an inner ng-repeat inside of an outer ng-repeat: Essentially, I am looking to implement something along these lines: <tr ng-repeat="milestone in order.milestones"> <td>{{mi ...

Exploring the Power of Ajax Integration with Mongodb

I have been trying to figure this out for a while now, but I'm lost. I am attempting to use Ajax to retrieve information from a collection named 'reizen' in MongoDB. My goal is to cycle through all elements within the collection and extract ...

Navigating through cors in next.js

Currently, I have set up my front end using Netlify and my backend using Heroku with Next.js For the fetch request on the front end, here is an example: fetch(`https://backendname.herokuapp.com/data`, { method: 'POST', headers: { & ...

Is there a way to transform a stringified array into an array in JavaScript if I do not have access to the original string?

Recently, I encountered a challenge where I had an array of items enclosed within "", and not '' (if that distinction matters): "['item 1', 'item2', 'item 3']" I am interested in converting it to ...

Increase the quantity with animation

I am attempting to increment a number within an element on the page. However, I require the number to have a comma included while the increment should only increase by 1 digit every second. The code is currently functional, but I am facing a dilemma regar ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

How to Test React Js API Calls with Jest?

I'm currently in the process of writing test cases for my API call function, but I'm encountering difficulties as I am unable to successfully run my tests. Below is the code for the API call function and the corresponding test cases. export async ...

Jpicker is renowned for its transparency feature

I am currently using the Jpicker jpicker-1.1.6.js script which can be found at Below is a snippet of my code: <script type="text/javascript"> $(function() { $.fn.jPicker.defaults.images.clientPath='/img'; var ...

Implementing script loading within the Angular scope

I'm attempting to load a custom script from the database based on client-side logic. I am having trouble figuring out how to make it function properly. Here is my controller code: 'use strict'; angular.module('youshareApp') . ...

Posting a string using AJAX to the Java backend through JavaScript

I'm currently working on a comment section for a Web Client. There are two tables involved - one for the comments and another for the users. My goal is to send input data from HTML <input> tags to a Java Service where the data will be processed ...

Create a submit button using Vue.js for text input

Can anyone help with a beginner question? I have a form that includes a text field. When I type something in and press enter, no result shows up. However, when I type something in and click the button, I get the desired result. Could someone guide me on ...

Supply a JSON parameter as a variable into the .load() function

When a button is clicked, I am attempting to load a page using the .load() method with a POST request. The URL parameters are generated and displayed as JSON formatted in the button attribute btn-url. Problem: The parameter is not being passed to the .loa ...

Acquiring the index of a selector event within a list of dynamic elements

I am seeking guidance on how to go about solving the issue of obtaining an event index. I have a hunch that closures might play a role in the solution and would appreciate some insights. Initially, I dynamically build an HTML5 video container using an aja ...

Deactivating the Grid and its offspring in React.js MUI

Is it possible to Disable the Grid (MUI Component) and its Children in React js? Additionally, how can we Disable any Container and its items in React js, regardless of the type of children they have? For example: <Grid item disabled // ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

What significance does it hold when an unhandled rejection event lacks a reason field?

Our app tracks client-side errors using Rollbar, but we keep encountering a not very helpful error message from Safari and Chrome: [unhandledrejection] error getting `reason` from event Upon investigation, I found that this message is generated by Rollbar ...