子组件如何才能使用父组件里的方法呢?下面这篇博客写了三种方法,大家可以参考。
(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使用父组件的函数,是没有办法通过函数访问到父组件里的数据的。