vue子组件获取父组件几种方法

1、使用this.$parent.event直接调用

//父组件
<template><div><child></child></div>
</template>
<script>import child from '~/components/dam/child';export default {components: {child},methods: {father() {console.log('提交');}}};
</script>//子组件
<template><div><button @click="submit()">点击</button></div>
</template>
<script>export default {methods: {submit() {this.$parent.father();}}};
</script>

2、通过$emit触发一个事件,父组件监听

//父组件
<template><div><child @father="father"></child></div>
</template>
<script>import child from '~/components/dam/child';export default {components: {child},methods: {father() {console.log('提交');}}};
</script>//子组件
<template><div><button @click="submit()">点击</button></div>
</template>
<script>export default {methods: {submit() {this.$emit('father');}}};
</script>

3、使用props

//父组件
<template><div><child :father="father"></child></div>
</template>
<script>import child from '~/components/dam/child';export default {components: {child},methods: {father() {console.log('提交');}}};
</script>//子组件
<template><div><button @click="submit()">点击</button></div>
</template>
<script>export default {props: {father: {type: Function,default: null}},methods: {submit() {this.father()}}};
</script>

三种区别: 三种都可以实现子组件调用父组件的方法,但是效率有所不同

this.$parent.event可以调用父组件身上的方法,无需绑定在子组件身上。缺点:有时候会失效,暂未发现触发点,不建议使用。
$emit可以调用父组件在子组件身上自定义的事件,需要用@前缀。建议使用此种方式
props可以调用父组件绑定在子组件身上的事件,需要:前缀。在router-view身上使用失效


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部