[Vuejs]-Vue.JS: Communication with component

0👍

Move your showModal variable to your App.vue and pass it to your AddUser component as a prop. Inside your Header and AddUser components you will need to update the showModal value by emitting a show-modal-event with the value true or false depending on if you want to show or hide the modal. Listen for the event in App.vue and update it’s local data showModal value with the $events value.

Here is an example. ** FYI this code isn’t tested so there might be typos.

Header.vue

<template>
    <header>
        <h2>{{title}}</h2>
        <p>{{description}}</p>
        <div class="text-center btn-class">
            <button @click="$emit('show-modal-event', true)">Add Vehicle</button>
        </div>
    </header>
</template>

<script>
export default{
    name: 'Header',
    props: {
        title: {
            type: String,
            default: 'Title!!',
        },
        description: {
            type: String,
            default: 'Description!!',
        }
    }
}
</script>

AddUser.vue

<template>
    <div>
        <transition name="fade" appear>
            <div class="modal-overlay" v-if="showModal" @click="$emit('show-modal-event', false)"></div>
        </transition>
        <transition name="slide" appear>
            <div class="modal" v-if="showModal">
                <h3>Enter your vehicle detail</h3>
                <div class="body">
                    <form @submit="onSubmit">
                        <div class="form-group">
                            <input type="text" v-model="name" name="name" class="form-control" placeholder="Enter your name">
                        </div>
                        <br><br>
                        <div class="form-btn form-group text-center">
                            <Button type="submit" text="Add" color="#2BA0A3" />
                        </div>
                    </form>
                </div>
            </div>
        </transition>
    </div>
</template>
<script>
import Button from './Button'
export default {
    name: 'AddUser',
    data(){
        return {
            name: ''
        }
    },
    props: {
        showModal: {
            type: Boolean,
            default: false
        }
    },
    components: {
        Button
    },
    methods: {
        onSubmit(e){
            e.preventDefault()
            if(!this.name){
                alert('Please enter name.')
            }
        },
    }
}
</script>

App.vue

<template>
    <div class="container">
        <Header @show-modal-event="showModal=$event"  />
        <AddUser @show-modal-event="showModal=$event" :showModal="showModal" />
    </div>
</template>

<script>
import Header from './components/Header'
import AddUser from './components/AddUser'

export default {
    name: 'App',
    components: {
        Header,
        AddUser,
    },
    data(){
        return {
            showModal: false,
        }
    },
}
</script>

Leave a comment