不推荐使用本文的方法,建议使用 props 和 emit
方法来自:stackoverflow.com/questions/55316490,在用这个方法前可以先试试 this.$refs[‘子组件’].doSth(),比下文的方法简单。
子组件
export default {
methods: {
doSth() {
console.log('子组件的 doSth 方法');
},
},
mounted() {
let self = this;
self.$emit('callback', {
doSth: () => self.doSth(),
});
},
};
父组件
<template>
<子组件 @callback="v => $options.callbackHandle = v" />
</template>
<script>
export default {
data() {
},
callbackHandle: {
doSth: () => {},
},
methods: {
// 调用子组件中的方法
doChildMethod() {
let self = this;
self.$options.callbackHandle.doSth();
},
},
};
</script>