vue 父组件调用子组件的方法,子组件调用父组件方法

首先看代码:

1、父组件:

<template>
	<div>
		<div v-if="!userShow">
			父组件内容区
			<el-button @click="lookUserInfo(scope.row)">&nbsp;查看</el-button> 
		</div>
		<!-- 子组件 -->
		<user-manager  v-if="userShow"  @close="showUserInfo" ref="child"> </user-manager>	
	</div>
</template>
<script>
	//导入用户页面
	import userManager from '../userManager.vue';
	export default {
	 	name:'taskManager',
	 	components:{userManager},
	 	data() {
	 		return {			
				userShow:false,				
			}
		},
		methods: {
			//显示子组件,隐藏父组件
			lookUserInfo(row) {
				this.userShow = true;
				this.$refs.child.chlidMethods
			},
			//此方法,子组件会调用,调用返回父页面:隐藏子组件,显示父组件
			showUserInfo() {
				this.userShow = false;
			},
		}
	}	
</script>

2、子组件:

<template>
	<div>
		<!-- 返回父页面按钮 -->
		<div>
            <el-button @click="goToParent"> &nbsp;&nbsp;返回</el-button>
        </div>
		<div class="white-bg margin auto">
			<el-table>
				数据表格展示区	
			</el-table>
		</div>
	</div>
</template>
<script>
	export default {
	 	name:'userManager',
	 	data() {
	 		return {	
			}
		},	
		methods: {
			goToParent() {
				//调父页面方法
			    this.$emit('close');
			}
			chlidMethods() {
				console.log("父组件调子组件方法了")
			}
		}
	}	
</script>

重点说明:

       1:、在父组件中

       父组件调用子组件步骤:
      (1)、导入子组件:import userManager from '../userManager.vue';
      (2)、引入组件:  components:{userManager},
      (3)、在要使用的地方写上子组件标签:<user-manager></user-manager>  注意不是驼峰命名法,用-连接
      (4)、自定义ref属性名: ref="child" child这个名字可以随意取

      (5)、在子组件中添加chlidMethods方法
      (6)、调用:this.$refs.child.chlidMethods    chlidMethods这个是子组件中的方法

        2、在子组件中:

        子组件调用父组件步骤:
       (1)、在父组件中添加@close属性:<user-manager @close="showUserInfo"> </user-manager>  close这个名字可以任意取
       (2)、在父组件中添加showUserInfo方法  名字任意取。名字与子组件无任何关系,只有close子组件会用到    
       (3)、子组件调父组件方法:this.$emit('close');

猜你喜欢

转载自blog.csdn.net/weixin_40841731/article/details/84027602