以父组件内的el-dialog和子组件内的el-form为例,进行父子组件方法调用与动态组件的灵活应用做讲解:
父组件:
<el-dialog
title="提示"
:visible.sync="dialogVisible"
width="30%" >
<components :is="childrenCom" :ref="childrenCom" :nameCom ="childrenCom" @close="close" /> // 动态组件
<span slot="footer" class="dialog-footer">
<el-button @click="changeCom">切换组件</el-button>
<el-button type="primary" @click="click">确 定</el-button>
</span>
</el-dialog>
<script>
components:{
first,
second
},
data(){
return:{
childrenCom:'first',
dialogVisible:true
}
},
methods:{
click(){
this.$refs[`${this.childrenCom}`].submitForm() // 调用 子组件内的方法
},
changeCom(){
this.childrenCom = 'second' //切换组件
},
close(data){
if(!data){
this.dialogVisible = data; // 关闭弹窗
this.$refs[`${this.childrenCom}`].resetForm() // 调用 子组件内的方法
}else{
this.$message('这是一条消息提示');
}
}
}
</script>
子组件:
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="活动名称" prop="name">
<el-input v-model="ruleForm.name"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>\
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
<script>
export default {
props:{
nameCom;{ type:String,default:()=> ''}
},
data() {
return { ruleForm: { name: '' }},
rules: { name: [ { required: true, message: '请输入活动名称', trigger: 'blur' } ] },
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
if(this.nameCom === 'second'){
this.$emit('close', false) // 校验成功,若符合条件,调用父组件方法,关闭弹窗
}else{
this.$emit('close', true) // 校验成功,不符合条件,提示失败
}
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
</script>