Vue中子组件调用父组件的方法,这里以下三种方法提供参考
第一种方法是直接在子组件中通过this.$parent.event来调用父组件的方法
父组件
<template>
</template>
import child from ../components/dam/child';
exportdefault{
components: {
child;
},
methods: {
fatherMethod() {
console.log('测试');
}
}
};
子组件
<template>
点击
</template>
exportdefault{
methods: {
childMethod() {
this.$parent.fatherMethod();
}
}
};
第二种方法是在子组件里用$emit向父组件触发一个事件,父组件监听这个事件就行了。
父组件
<template>
<div class="container" style="margin: auto">
<h1 style="text-align: center">Vip会员</h1>
<Hello @handleclick="handleClick"></Hello>
</div>
</template>
<script>
import Hello from "../components/hello.vue";
export default {
components: {
Hello,
},
methods: {
handleClick() {
console.log("这是父组件的方法!");
},
},
};
</script>
<style scoped>
h1 {
text-align: center;
}
</style>
//子组件 hello.vue
<template>
<div
id="myChart"
:style="{ width: '500px', height: '300px', margin: 'auto' }"
></div>
</template>
<script>
export default {
name: "hello",
data() {
return {
msg: "Welcome to Your Vue.js App",
};
},
created() {
this.$emit('handleclick');
//调用方式时切记是小写
},
};
</script>
//调用成功如下
第三种是父组件把方法传入子组件中,在子组件里直接调用这个方法
父组件
<template>
</template>
importchildfrom'~/components/dam/child';
exportdefault{
components: {
child
},
methods: {
fatherMethod() {
console.log('测试');
}
}
};
子组件
<template>
点击
</template>
exportdefault{
props: {
fatherMethod: {
type:Function,
default:null
}
},
methods: {
childMethod() {
if(this.fatherMethod) {
this.fatherMethod();
}
}
}
};