3.1 需求
效果:
3.2 实现
父组件:
父组件设计包含一个按钮,一个el-popover、一个子组件
xml
<div>
<el-popover placement="bottom" trigger="click" ref="popover">
<dialog-comp @save="save" ref="dialog"></dialog-comp>
<el-button slot="reference" type="primary" size="mini">点击出现弹框</el-button>
</el-popover>
</div>
父组件的工作:
拿到子组件提交的值;关闭popover、清空子组件弹框的数据
kotlin
save (v) {
this.inputValue = v.value
this.$refs.popover.doClose() // 关闭弹框
this.$refs.dialog.reset() // 清空数据
}
子组件:
子组件由一个单纯的表单组成
xml
<el-form :model="form" ref="form" size="small" :rules="rules">
<el-form-item label="作业名称" prop="value" required>
<el-input v-model="form.value"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="save" style="float: right" >保存</el-button>
</el-form-item>
</el-form>
子组件的工作:
完成表单的校验和提交表单的数据
kotlin
save () {
this.$refs.form.validate((valid) => {
if (valid) {
this.$emit('save', this.form)
} else {
return false
}
})
},
抛出一个清空表单的方法,便于调用
kotlin
reset () {
this.$refs.form.resetFields()
}
完整的代码如下:
父组件:
xml
<template>
<div class="about" ref="box">
<el-input v-model="inputValue" style="margin-bottom: 50px"></el-input>
<el-popover placement="bottom" trigger="click" ref="popover">
<dialog-comp @save="save" ref="dialog"></dialog-comp>
<el-button slot="reference" type="primary" size="mini"
>点击出现弹框</el-button
>
</el-popover>
</div>
</template>
<script>
import DialogComp from '@/components/DialogComp.vue'
export default {
components: {
DialogComp
},
data () {
return {
inputValue: ''
}
},
methods: {
save (v) {
console.log(v)
this.inputValue = v.value
this.$refs.popover.doClose() // 关闭弹框
this.$refs.dialog.reset() // 清空数据
}
}
}
</script>
<style scoped>
.about {
width: 500px;
margin: auto;
}
</style>
子组件:
xml
<!-- -->
<template>
<el-form :model="form" ref="form" size="small" :rules="rules">
<el-form-item label="作业名称" prop="value" required>
<el-input v-model="form.value"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="save" style="float: right"
>保存</el-button
>
</el-form-item>
</el-form>
</template>
<script>
export default {
data () {
return {
form: {
value: ''
},
rules: {
vaule: {
required: true,
message: '必填',
trigger: blur
}
}
}
},
methods: {
save () {
this.$refs.form.validate((valid) => {
if (valid) {
this.$emit('save', this.form)
} else {
return false
}
})
},
reset () {
this.$refs.form.resetFields()
}
}
}
</script>