父组件代码
<template>
<div>
<button @click="callChildFunction">调用子组件函数</button>
<ChildComponent ref="childComponent"></ChildComponent> // ref="childComponent" 这个很重要
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
methods: {
callChildFunction() {
this.$refs.childComponent.childFunction();
},
},
};
</script>
<script>
import { getCurrentInstance } from 'vue'; // 导入读取全局变量的方法
export default {
setup() {
const { proxy } = getCurrentInstance(); // 导出全局变量
console.log(proxy.$refs.childComponent.childFunction());
}
}
</script>
子组件代码
在子组件,只需要导出需要读取的就行了
<template>
<div>
{{ message }}
</div>
</template>
<script>
export default {
data() {
return {
message: '我是子组件',
};
},
methods: {
childFunction() {
console.log('子组件函数被调用!');
},
},
};
</script>
<script>
export default {
setup() {
childFunction() {
console.log('子组件函数被调用!');
},
return {childFunction} // 确保最后这个函数暴露出来
}
}
</script>