Can't vue.js call parent to child events?

Asked 1 years ago, Updated 1 years ago, 110 views

For example, to open a modal that is reused in multiple locations
Is it impossible to call a child's method from the parent without giving the parent a state?
Would you like to write it in the following way?

All you have to do is v-bind true false in the parent, but the parent manages the child's state. Somehow I feel uncomfortable...

Child Components

<template>
    <divid="modal" v-if="showModal">
       Modal!
       <button type="button"@click="close()">Close</button>
    </div>
</template>

<script>
    export default {
        data:function(){
            US>return{
                showModal: false
            }
        },
        methods: {
            show(){
                This.showModal=true;
            },
            close(){
                This.showModal=false;
            },
        }
    };
</script>

Parent Components

import Vue from 'vue';
import modalComponent from '../components/modal.vue';
var app = new Vue({
    el: '#app',
    data: {
    },
    components: {
        modal —ModalComponent
    },
    methods: {
        show(){
            modal.show();
        },
        close(){
            modal.close();
        }
    }
});

HTML in which the parent component is installed

<divid="myBukken">
    <button type="button"@click="show()">Modal open</button>
    <modal></modal>
</div>

javascript vue.js

2022-09-30 19:02

1 Answers

I think it is more natural for the parent component to control the display/hide of child components with v-if.The official demo below also does so.

Official example-Modal
https://v2.vuejs.org/v2/examples/modal.html


2022-09-30 19:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.