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

Breaking down objects and setting default values

In need of assistance with resolving an issue related to default parameters and object destructuring. The 'product' object that I am working with has the following structure: { name: "Slip Dress", priceInCents: 8800, availableSizes ...

retrieve Excel document via POST request

I have a scenario where my API endpoint accepts JSON input and returns an Excel file directly instead of providing a link to download the file. How can I use JQuery AJAX to download this file? Here is the backend code snippet: public function postExcel() ...

Utilizing Vue.js: Dynamically Rendering Components Based on Routes

I needed to hide some components for specific Routes, and I was able to achieve this by using a watcher for route changes that I found in this StackOverflow question - Vuejs: Event on route change. My goal was to not display the header and sidebar on the c ...

Execute local server's unit tests using a Gulp task

I am currently faced with the challenge of running automated unit tests in the terminal for a library application that utilizes the History API internally. To achieve this, I am utilizing Babel to transpile and consolidate my Mocha/Chai/Sinon unit tests in ...

Issue with AngularJS compatibility on first generation iPad

Having trouble with my first generation iPad while trying to implement a basic ngRoute and ngAnimate setup. It's working fine on desktop and iPhone 6, but not on the iPad. The error message I'm encountering is: Error[$injector:modulerr]http://e ...

What is the best way to divide files in a Vue.js-based spa into both public and private sections?

Looking to divide my Vue.js and Ionic SPA app into a public section (featuring just login, password request, and minimal content) and the remaining functionality... I've come across the possibility of implementing a Multi-Page Application utilizing w ...

Issues with non-functional plugins that utilize AJAX functionality

I am encountering an issue with my code that includes an ajax script for deleting a record, along with an animation during the deletion process. However, when I try to integrate the ajax script with plugins for confirmation, it seems to not be working prop ...

Automatically close one option upon opening another

Displayed below is the HTML code that I have printed with echo: <input id="58" readonly="readonly" class="cell_to_edit" value="Accepted"> <span id="58" class="toggle_status"> <select class="status_change"> <option>Ac ...

Activate the Select List to Appear Only When a Search is Conducted

Currently, I have implemented the react-select API in order to provide language options for selection. <Select isMulti name="langs" options={langOptions} defaultValue={{ value: "English", label: "English", nativeNam ...

Divide a string into smaller sections beginning at " ] " and concluding with "As"

In Microsoft SQL Server 2008 R2, I have fetched a string from a stored procedure using the query: EXEC sp_helptext 'MyStoredProcedureName';. My task is to divide this string into arrays or substrings that start from the closing parenthesis "]" a ...

Using jQuery to retrieve the nth child from a table after dynamically creating it with AJAX

When using AJAX in the code below, I fill and create simple data after retrieving it. $.ajax({ method: 'GET', url: '/analyzePage/searchTag/' + tagName, contentType: false, processData: false, success: function (data ...

Create proper spacing for string formatting within an AngularJS modal

I am working with a popup that displays output as one string with spaces and newline characters. Each line is concatenated to the previous line, allowing for individual adjustments. Test1 : Success : 200 Test2 : Su ...

Troubleshooting a problem with data retrieval in Hygraph and Next JS

I'm currently facing an issue while attempting to fetch data from Hygraph in a fresh Next JS application. The error message I'm encountering is: Error: Cannot read properties of undefined (reading 'map'). As a beginner in both technolo ...

When executing a function, the previous React state continues to linger

Why is the updateUser() function only updating the last user instead of all users despite using useCallback and including users as a dependency? The expected output after clicking the update button should be: {"id":1,"name":"John& ...

Does utilizing the i18n module solely for the purpose of translating route names seem excessive?

My coding habit is to write everything in English for easy understanding by developers, but I'm encountering a dilemma while using Nuxt. All the page components I create are named in English, whereas our user base speaks a different language. Should I ...

Is there a way to differentiate between a preflight request and the actual request?

Currently, I am utilizing CORS to transmit data to a server located on a different domain. Initially, the browser dispatches the preflight request to verify the server, followed by the main request. My goal is to identify when the request is in the "prefl ...

Leveraging React's UseEffect() to retrieve information from GraphQL

I am currently attempting to retrieve data from graphQL. I understand that by placing a function inside the react UseEffect(), I can trigger the function once the data is updated and structured. However, while working on a chatroom feature, I am facing an ...

Exploring the connection between `item-text` and Vue's render function

I'm currently attempting to utilize the render function in Vue to render a template strictly using it. In this particular scenario, I am trying to bind the item-text on the attributes object ... but unfortunately, my efforts have been unsuccessful. ...

Unlock maximum screen viewing on your custom video player with these steps to activate fullscreen

I'm having an issue with my basic video player - when toggling fullscreen, it doesn't fill the whole screen even though I tried using .fullscreen{width:100%} without success after searching for a solution. html <div class='player-contai ...

Refresh the vue-chart component in a nuxt.js application

I'm currently working on a nuxt project and I need to incorporate some charts into it. I'm using vue-chartjs as a plugin for this purpose. However, the issue I'm facing is that the chart data is fetched after the chart has already been drawn ...