子组件想使用父组件的方法函数--通过props传递实现函数传递

本文探讨了Vue中子组件如何正确调用父组件传递的方法,并解决了this指向问题导致的错误。通过实例展示了使用props传递方法时的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

子组件如何才能使用父组件里的方法呢?下面这篇博客写了三种方法,大家可以参考。

(57条消息) vue子组件怎么调用父组件的方法_ぎ风な的博客-优快云博客_vue子组件调用父组件中的方法

今天我们主要讨论一下使用props传递方法函数存在的注意事项--this的指向问题

上代码

父组件

<template>
  <p>
    <child :requestMethod="requestMethod"></child>
  </p>
</template>
<script>
  import child from './child';
  export default {
    components: {
      child
    },
    data(){
		return{
            currentSearch :'owner',
        }
    },
    methods: {
      requestMethod(){
		//console.log(this.popupPage)
		if(this.currentSearch == 'owner')
			return this.$u.api.getUsers
		if(this.currentSearch == 'status')
			return this.$u.api.getStatuses
		
	  },
    }
  };
</script>

子组件

<template>
  <p>
    <button @click="childMethod()">点击</button>
  </p>
</template>
<script>
  export default {
    props:['requestMethod'],
    data() {
		return {
			popupPage:0,
		};
	},
    methods: {
      async childMethod() {
        let request = this.requestMethod()
		const list = await request()
        ......
      }
    }
  };
</script>

一运行,控制台报错:request is not a function

逐步debugger,发现子组件调用this.requestMethod()返回值为undefined,

并没有拿到正确的返回值,

我再debugger,

发现父组件的if判断值this.currentSearch是undefined,怎么会呢,this.currentSearch是有值的,

那问题就在this指向上了,

我在父组件函数加了一句console.log(this.popupPage),结果正确输出了子组件的popupPage值。

结论:props传递的方法函数,函数中this指向调用者。

如果子组件使用props使用父组件的函数,是没有办法通过函数访问到父组件里的数据的。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值