在Vue中我们想在子组件调用父组件方法时,可以通过在子组件接收父组件传入的this去调用父组件的方法。
父组件
<template>
<div>
<v-child :home="this" />
</div>
</template>
<script>
import child from "./components/child.vue";
export default {
name: "App",
components: {
"v-child": child,
},
methods: {
run() {
console.log("子组件调用父组件方法");
},
},
};
</script>
子组件
<button @click="fatherMethod">子组件调用父组件方法</button>
props: {
home: {},
},
methods: {
fatherMethod() {
this.home.run();
console.log(this.home);
},
},
也可以直接在子组件通过$parent 获取到父组件属性或方法
this.$parent.属性或方法
当我们又想在父组件直接调用子组件时,可以给子组件定义ref
<v-child ref="child" />
父组件主动获取子组件数据
this.$refs.child.属性或者方法