uni-app中组件间方法调用

本文介绍了在uni-app中如何实现子组件与父组件之间的方法调用。通过示例代码展示了使用$emit和$refs进行通信的方式,子组件通过$emit触发父组件方法,父组件则通过this.$refs调用子组件的方法。

在此总结下,供参考!

一、先上结果图,如下:

 

 

二、项目说明

红色圈起来的为子组件,绿色圈起来的为父组件。

uni-app项目,所以具体组件引入流程不在详细说明,直接列出代码。

 

三、代码

1、子组件child.vue

<template>
	<view class="" @click="getFatherMethod">
		点击调用父组件中的方法
	</view>
</template>

<script>
	export default{
		methods:{
			// 定义子组件中的方法
			childMethod(){
				console.log("我是子组件中的方法childMethod。。。。。。")
			},
			
			// 调用父组件中的方法fatherMethod
			getFatherMethod(){
				this.$emit("getValue");
				
			}
	
		}
	}
</script>

<style>
</style>

2、父组件index.vue

<template>
	<view class="father-wrap">
		<text>父组件页面show</text>
		<child @getValue="fatherMethod" ref="sonMethod" :res="list" :kk="df"></child>
	    <text  @click="getChildMethod">点击调用子组件中的方法</text>
	</view>
</template>

<script>
	// 引入子组件
	import child from '../../components/child.vue'
	export default {
		components:{
			child
		},
		methods:{
			// 定义父组件中的方法
			fatherMethod(){
				console.log("我是父组件里的方法fatherMethod。。。。。。")
			},
			
			// 调用子组件中的方法childMethod
			getChildMethod(){
				this.$refs.sonMethod.childMethod();
			}
		}
	}
</script>

<style>
	.father-wrap{
		font-size:30upx;
		line-height: 80upx;
		letter-spacing: 4upx;
	}
</style>

说明:子组件调用父组件中的方法,用$emit方法。

           父组件调用子组件中的方法用:子组件上定义ref="refName",  父组件的方法中用 this.$refs.refName.去调用子组件方法

 此处即为    ref="sonMethod       this.$refs.sonMethod.childMethod();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值