1

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??

0

1 Answer 1

1

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?

Sign up to request clarification or add additional context in comments.

3 Comments

the template is part of the App.vue component. should I add a template: in app component? It cannot run properly without have the render and el properties there in app.js
@zatyh, Remove id='app' And create another other dom element with this ID where your root instance can mount. Also, move the method showModal to App Component instead of Root Instance.
Hey, thanks I did what you said it works, really appreciate it Harshal

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.