uni-app中組件間方法調用

在此總結下,供參考!

一、先上結果圖,如下:

 

 

二、項目說明

紅色圈起來的爲子組件,綠色圈起來的爲父組件。

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();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章