Search code examples
javascriptvue.jsref

VueJS Element Reference Not Found


in VueJS I am wanting to reference a modal element via ref attribute in VueJS. I've used them before, but in this set up something's not right making it not work and gives the error:

TypeError: this.$refs.modal is undefined

I am accessing the reference via the app.js file.

here's my main app.vue template code:

    <template>
    <main class="main" id='app'>
        <div v-if="$root.bLoading" class="page-loader">
            <div class="page-loader__spinner">
                <svg viewBox="25 25 50 50">
                    <circle cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10" />
                </svg>
            </div>
        </div>
        <span v-else v-cloak>
            <header-nav></header-nav>
            <router-view></router-view>
            <footer></footer>
        </span>
        <main-modal ref="modal"></main-modal>
    </main>
</template>

Here's my app.js code trying to access the reference:

 let app = new Vue({
        el: '#app',
        render:h=>h(App),
        data : function(){
            return {

            }
        },
        router,
        methods : {
            showModal : function(modal_name="",modal_data={}){
                this.$refs.modal.showModal(modal_name,modal_data);
            },
        }
    });

Why is this reference element not being found??


Solution

  • This is happening because ref="modal" is part of App component and you are trying to access that referenced component from your root instance. The instance ref is not available outside of the component App. Try moving your showModal method inside App component.

    Note: there is some discrepancy with your code. Your #app element has a template and at the same time, you are using render function which is supposed to render App component. That is contradictory. Is your template in the example really part of Root Instance or App component?