search

Home  >  Q&A  >  body text

javascript - Problems with component division and combination use in vue

I am new to Vue. I am currently doing a small exercise with a grid component and a dialog component. There is a delete button for each row in the grid. After clicking, a pop-up window will prompt whether to delete it. The gird component is as shown below:

dialog component picture below:

Create a vue instance in App.vue and introduce the grid component. Now I don’t know whether the dialog should be introduced in App.vue or in the grid. If introduced in the grid, wouldn't the grid be too deeply coupled with the dialog? If a dialog is introduced in the App, controlling whether the dialog is displayed or not must be controlled in the App, but I feel that closing the dialog should be controlled by the dialog.
My current approach is to introduce gird and dialog in App.vue respectively. When the delete button is clicked, an event is emitted in gird, the event is monitored in the App, and the value that controls whether the dialog is displayed is changed to true. When the dialog close button is clicked, an event is emitted. The App listens for the event and changes the value that controls whether the dialog is displayed to false. I feel like it shouldn't be handled this way.
Please give me some guidance from seniors on how to better divide and combine components. Thank you!

漂亮男人漂亮男人2775 days ago603

reply all(1)I'll reply

  • 習慣沉默

    習慣沉默2017-05-19 10:39:17

    Use v-model to 'disguise' dialog as input to achieve parent-child bidirectional data flow

    Subcomponent:

    <template>
        <p v-if="value">
            <a href="javascript:;" @click="close">关闭</a>
        </p>
    </template>
    <script>
    export default {
        props:{
            value:{
                type:Boolean,
                default:false
            }
        },
        data() {
            return {
                isShow: this.value
            }
        },
    
        methods: {
            close() {
                this.isShow = false
                this.$emit("input", this.isShow)
            }
        }
    }
    </script>

    Father:

    <Child v-model="showDialog"></Child>
    data:{
        showDialog:false
    }

    In this way, the parent changes showDialog to hide/show it, and calling close on the child component will also update the value of showDialog

    Official document https://cn.vuejs.org/v2/guide... Form input component using custom events

    reply
    0
  • Cancelreply