fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[vue] 如何在子组件中访问父组件的实例?

Open haizhilin2013 opened this issue 7 years ago • 7 comments

[vue] 如何在子组件中访问父组件的实例?

haizhilin2013 avatar Jun 22 '19 21:06 haizhilin2013

this.$parent

yin-pathfinder avatar Jun 28 '19 07:06 yin-pathfinder

this.$parent拿到父组件实例 this.$children拿到子组件实例(数组)

lovelmh13 avatar Jun 28 '19 15:06 lovelmh13

this.$parent

qq326943819 avatar Jun 28 '19 18:06 qq326943819

vue中如果父组件想调用子组件的方法,可以在子组件中加上ref,然后通过this.$refs.ref.method调用(https://www.cnblogs.com/jin-zhe/p/9523029.html) Vue中子组件调用父组件的方法,这里有三种方法提供参考: 1:直接在子组件中通过this.$parent.event来调用父组件的方法 2:在子组件里用$emit向父组件触发一个事件,父组件监听这个事件 3:父组件把方法传入子组件中,在子组件里直接调用这个方法 (https://www.cnblogs.com/jin-zhe/p/9523782.html)

HeMin0919 avatar Jul 23 '19 08:07 HeMin0919

$refs也行

radio-qq avatar Dec 31 '20 01:12 radio-qq

子组件访问父组件:$parent

但少用 $parent 和 $children

它们主要用来应急,更推荐用 props 和 events 实现父子组件通信

如果子组件是公共组件,到处用,你在当前这个父组件下用没问题,但在别的地方用这个子组件,你还需要 $parent 吗?$parent 有对应的属性或方法吗?很容易产生bug,不利于调试。

所以这种写法是不被推荐的,官方文档有写。

hyj443 avatar Oct 19 '21 03:10 hyj443

this.$emit

Azenmy avatar Oct 22 '21 07:10 Azenmy