1
votes

This is my first proper Vue JS project...I've searched Stack O and can't find anything that specifically addresses my issue, but I apologise if this has already been asked.

The Problem

I have two components, the parent is the page layout, while the child is a module of that page. When somebody clicks on a button in the child component, I want to trigger a function in the parent component.

The $emit part of the process is firing correctly according to the VueJS Dev Tools, but the function in the parent doesn't trigger.

Where am I going wrong?

Here is my abberviated code (I've removed anything not related to the issue)...

Parent Component

<template>
    <div :toggle-nav="showHideNav" :class="navState">
        <div class="wrapper">
            <layout-toolbar></layout-toolbar>
        </div>
    </div>
</template>
<script>
    import layoutToolbar from '~/components/layout/toolbar.vue'

    export default {
        components: {
            layoutToolbar,
        },
        data: function() {
            return {
                navState: 'menu-closed'
            }
        },
        methods: {
            showHideNav: function(event) {
                if (this.navState == 'menu-closed') {
                    this.navState = 'menu-open'
                } else {
                    this.navState = 'menu-closed'
                }
            }
        }
    }
</script>

Child Component

<template>
    <div class="toolbar" role="navigation">
        <div class="tools" role="group">
            <button 
                class="button-icon" 
                aria-label="Open Navigation" 
                @click="$emit('toggle-nav')">
                    <i aria-hidden="true" class="far fa-bars" title="Open Navigation"></i>
                    <span class="sr-only">Open Navigation</span>
            </button>
        </div>
    </div>
</template>

Do I need to be making use of props?

Appreciate any help that can be offered.

1

1 Answers

2
votes

You have to pass a function as a prop and then emit that function from your child component. So your parent template looks like this .

<template>
    <div :toggle-nav="showHideNav" :class="navState">
        <div class="wrapper">
            <layout-toolbar @showHideNav="showHideNav"></layout-toolbar>
        </div>
    </div>
</template>

And your child template looks like this

<template>
    <div class="toolbar" role="navigation">
        <div class="tools" role="group">
            <button 
                class="button-icon" 
                aria-label="Open Navigation" 
                @click="$emit('showHideNav',<pass-your-event-or-data>)">
                    <i aria-hidden="true" class="far fa-bars" title="Open Navigation"></i>
                    <span class="sr-only">Open Navigation</span>
            </button>
        </div>
    </div>
</template>