一、子组件调用父组件方法(父传子-方法)
场景:子组件是弹出框组件。当点击确定时,将新增的值增加到父组件的列表。就要调用父组件的getLIst()方法。
代码:
//父组件 利用@子组件方法名="父组件方法名",实现父传子-方法
<add-follow-record :open="open" :cancel="cancel" @toggleDialog="cancel" ref="followRecord"
@getList="getList"></add-follow-record>
/** 查询列表 */
getList() {
incrementDetail(this.incrementId).then(response => {
this.incrementIdData = response.data;
})
},
//子组件 调用新增接口时,利用this.$emit('方法名')方法,来调用父组件的方法
/** 新增对话框 */
submitForm() {
this.$refs["form"].validate((valid) => {
if (!valid) {
return;
}
this.$set(this.form, 'incrementId', this.incrementId)
// 添加的提交
incrementFollowCreate(this.form).then(res => {
if (res.data !== null) {
this.$modal.msgSuccess('已添加一条跟进记录!');
this.$emit('toggleDialog')
this.reset();
//调用父组件获取列表接口方法
this.$emit('getList')
}
})
});
},
二、子组件调用父组件值(父传子-值)
场景:场景如上,当在父组件点击新增时,需要将open传递给子组件,但是子组件不能直接修改父组件的值,这就需要使用props传递。
代码:
//父组件 利用:子组件定义的值='父组件值',实现父传子-值
<add-follow-record :open="open" :cancel="cancel" @toggleDialog="cancel" ref="followRecord"
@getList="getList"></add-follow-record>
data(){
// 是否显示弹出层
open: false,
}
//子组件 子组件通过props接收父组件传递过来的值
<el-dialog title="" :visible.sync="open" width="35%"></el-dialog>
//props有两种写法
//法一:
props:['open']
//法二:
props: {
open: {
type: String,//数据类型
required: true//默认值
},
}
三、父组件调用子组件方法/值(子传父-方法/值)
场景:场景如上,(1)当点击新增时,已经输入值,但是不点击确定,点击取消之后输入框还有值,这时候就需要在点击新增的时候,清空输入框的值。
(2)父组件想要获取到子组件的某个值并使用。
代码:
//父组件 父组件中添加ref属性,这样就可以获取子组件的dom的方法或值
<add-follow-record :open="open" :cancel="cancel" @toggleDialog="cancel" ref="followRecord"
@getList="getList"></add-follow-record>
/** 打开对话框 */
addFollowRecord() {
this.open = true;
//利用this.$refs.ref名称.子组件方法名可以调用子组件的方法(子传父-方法)
this.$refs.followRecord.reset()
//利用this.$refs.ref名称.子组件值可以将子组件的值赋值给父组件(子传父-值)
this.msg = this.$refs.followRecord.message
},
//子组件
data(){
message:'子组件数据'
}
/** 表单重置 */
reset() {
this.form = {
...
};
this.resetForm("form");
},