第一种 直接调用父组件方法,传值给子组件

在子组件中通过this.$parent.fatherMethods()调用父组件的方法

父组件

<template>
		<view class="content">
			// 子组件
			<comhead :title="'采购商品'"></comhead>
		</view>
	</template>
	
	<script>
		export default{
			methods:{
				// 父组件方法
				fatherBack(){
					console.log('父组件方法')
				}
			}
		}
	</script>
	
	<style scoped lang="scss" scr="../../style/googsChoose.scss">
	</style>

我父组件没有引入和注册子组件是因为符合easycom规范,目录是这样的就行,自己去查uniapp
在这里插入图片描述

子组件
*需要注意的是在H5端需要this.$parent.$parent.fatherMethods()才可以成功调用

<template>
	<view class="head">
		<button plain hover-class="click" class="iconfont back icon" @click="back">&#xe600;</button>
		<view class="title">{{title}}</view>
		<view class="icon">
			<slot name="right"></slot>
		</view>
	</view>
</template>

<script>
	export default {
		props: {
			// 接收父组件的传值
			title: {
				type: String,
				default: ''
			},
		},
		methods: {
			back() {
				// #ifdef H5 
				if (this.$parent.$parent.fatherBack != undefined) {
					this.$parent.$parent.fatherBack();
					return;
				}
				// #endif

				if (this.$parent.fatherBack != undefined) {
					// 调用父组件方法
					this.$parent.fatherBack();
					return;
				}
				uni.navigateBack()
			}
		}
	}
</script>

第二种 通过监听间接调用父组件方法,传值给父组件

子组件通过$emit向父组件触发一个事件,然后父组件再监听这个事件,通常也是通过这种方法实现子组件向父组件传值

父组件

<template>
  <div>
  	// 第三步,监听子组件触发的fatherMethod事件,执行fatherMethods方法
    <child @fatherMethod="fatherMethods"></child>
  </div>
</template>
<script>
  import child from '~/components/child/child';
  export default {
    components: {
      child
    },
    methods: {
      // 第四步,执行方法并接收子组件的传值
      fatherMethods(e) {
        console.log('父组件方法',e);  // 父组件方法,0527
      }
    }
  };
</script>

子组件

<template>
  <div>
  	// 第一步
    <button @click="childMethod()">click</button>
  </div>
</template>
<script>
  export default {
    methods: {
      // 第二步
      childMethod() {
        this.$emit('fatherMethod', 0527);
      }
    }
  };
</script>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐