Vue子组件调用父组件方法案例详解
更新时间:2021年09月14日 09:03:25 作者:猫老板的豆
这篇文章主要介绍了Vue子组件调用父组件方法案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
一、直接在子组件中通过this.$parent.event来调用父组件的方法
<!-- 父组件 -->
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod () {
console.log('测试');
}
}
};
</script>
<!-- 子组件 -->
<template>
<div>
<button @click="childMethod()">点击</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$parent.fatherMethod();
}
}
};
</script>
二、在子组件里用$emit向父组件触发一个事件,父组件监听这个事件
<!-- 父组件 -->
<template>
<div>
<child @fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod () {
console.log('测试');
}
}
};
</script>
<!-- 子组件 -->
<template>
<div>
<button @click="childMethod()">点击</button>
</div>
</template>
<script>
export default {
methods: {
childMethod () {
this.$emit('fatherMethod');
}
}
};
</script>
三、父组件把方法传入子组件中,在子组件里直接调用这个方法
<!-- 父组件 -->
<template>
<div>
<child :fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod () {
console.log('测试');
}
}
};
</script>
<!-- 子组件 -->
<template>
<div>
<button @click="childMethod()">点击</button>
</div>
</template>
<script>
export default {
props: {
fatherMethod: {
type: Function,
default: null
}
},
methods: {
childMethod () {
if (this.fatherMethod) {
this.fatherMethod();
}
}
}
};
</script>
到此这篇关于Vue子组件调用父组件方法案例详解的文章就介绍到这了,更多相关Vue子组件调用父组件方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
深入探讨如何在Vue中使用EventBus实现组件间的高效通信
在现代前端开发中,Vue.js 作为一种流行的渐进式框架,广泛应用于各类 Web 项目的构建中,本文将深入探讨如何在 Vue 中使用 EventBus,实现组件间的高效通信,需要的可以了解下2024-11-11
vue-cli3使用postcss-plugin-px2rem方式
这篇文章主要介绍了vue-cli3使用postcss-plugin-px2rem方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-07-07
Element-ui el-tree新增和删除节点后如何刷新tree的实例
这篇文章主要介绍了Element-ui el-tree新增和删除节点后如何刷新tree的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-08-08


最新评论