vue之父子组件执行对方的方法
2024-09-05 09:56:09
一、子组件执行父组件中的方法
1、父组件将方法名传给子组件,子组件进行调用
父组件中:
<Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用户</Vbutton>
methods: {
addOneUser() { $('#addModal').modal('show')
}
}
子组件中:
<template> <button class="btn" :class="currentBtn" @click="handleClickParent"> <slot>按钮</slot> </button> </template>
props:{
typeBtn:String,
btnUserMethod:Function //验证类型接收父组件方法名
}, methods:{
handleClickParent(){
this.btnUserMethod(); //子组件调用父组件方法
}
},
2、子组件里用$emit
向父组件触发一个事件,父组件监听这个事件
父组件中:
<Vbutton typeBtn="success" :btnUserMethod="addOneUser" >添加用户</Vbutton>
methods: {
addOneUser() { $('#addModal').modal('show')
}
}
子组件中:
<template> <button class="btn" :class="currentBtn" @click="handleClickParent"> <slot>按钮</slot> </button> </template>
methods:{
handleClickParent(){
this.$emit('addOneUser'); //这里还可以向父组件传参,只需要父组件函数有对应的形参即可
}
},
}
二、父组件执行子组件中的方法
子组件:
//子组件Vbutton
childMethod(){
alert("我是子组件方法")
}
父组件:
<template>
<div>
<button @click="parentClick">点击</button>
<Vbutton ref="child" /> <!--使用组件标签-->
</div>
</template>
parentClick() {
this.$refs.child.childMethod("我是子组件里面的方法"); // 调用子组件的方法childMethod
},
(1)在子组件中写入相应的方法
(2)在父组件中引入子组件
(3) <Vbutton ref="mychild" /> 是在父组件中为子组件添加一个占位,ref="child"是子组件在父组件中的名字
(4)在父组件的方法中调用子组件的方法,很重要 this.$refs.child.childMethod("我是子组件里面的方法");
最新文章
- mysql 主主复制搭建用的命令
- JAVA Web day03--- Android小白的第三天学习笔记
- 如何从NFS文件系统启动
- MVC中使用AuthorizeAttribute做身份验证操作
- show index 之Cardinality (mysql)
- 0c-34-自动释放池
- JQ each
- Nodejs中Mongodb使用
- MVVM模式下 DataTemplate 中控件的绑定
- cain使用方法
- python3 判断字符串是否为纯空格组成的方法
- 使用.net core构建分布式SAAS系统(目录)
- VMware Workstation 10序列号:
- mongodb集群部署
- 工作笔记-table问题汇总(vue单文件组件)
- WIN10在loadrunner安装或path4插件安装时遇到的管理员阻止程序运行---解决方案(可用)
- win10 uwp 重启软件
- HTML5中的Web Storage(sessionStorage||localStorage)理解与简单实例
- d3.js(v5.7)力导向图(关系图谱)
- vue使用axios请求本地json文件出现404