SoFunction
Updated on 2025-04-04

Encapsulation method of implementing dialog in Vue2

Recently, when I looked at the company's previous projects, I found that many dialogs with more form content are written in the list component.

The query function of a list page already contains the search form, plus other functions in the list, such as: details, deletion, export, import, submission, etc., are written in this component, which is very cumbersome to maintain.

Therefore, when facing the need to add this pop-up content, it either jumps to route to a new interface or encapsulates a dialog component separately.

Here we take this opportunity to show the encapsulation of the dialog component.

There is only one dialog inside the component

The control visible variable of the dialog is best written in the component, and should not be written in the parent component to achieve it by passing props. Otherwise, it is not particularly elegant to maintain another variable in the parent component.

<template>
        <el-dialog 
            title="New"
            :visible="visibleDia"
            @close="closeDia"
            fullscreen
        >
        
            <!-- Customize pop-up content -->

            <div slot="footer">
                <el-button @click="saveInfo" type="primary">save</el-button>
                <el-button @click="closeDia" type="primary" plain>Cancel</el-button>
            </div>
        </el-dialog>
</template>
<script>
export default {
    name: 'SaveDialog',
    data() {
        return {
            visibleDia: false,
        }
    },
    methods: {
        openDia() {
             = true
        },
        closeDia() {
             = false
        },
        saveInfo() {
        // Tell the parent component that the save is successful			this.$emit('saveSuccess', true)
			()
		}
    }
}
</script>

Parent component call

A parent component binds a pop-up component when calling a pop-up componentrefAttributes, available through$refsCalling the nodeopenDiaMethod, open pop-up window;

Close the pop-up window is the logic in the pop-up window component, and you can close it yourself after the event is processed.

<template>
    <div>


		<!-- Other content on the page -->
		
		<el-button @click="handleAdd">New</el-button>
		
		<save-dialog
			ref="saveDialog"
			@saveSuccess="saveSuccess"
		 />
    </div>    
</template>
<script>
import SaveDialog from './'
export default {
    name: 'Index',
    components: { SaveDialog },
    methods: {
        handleAdd() {
            this.$()
        },
        saveSuccess() {
        	// When this method is called, it means that the new content of the pop-up window has been completed		}
    }
}
</script>

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.