父组件调用子组件的方法是通过expose和ref来实现的,我们可以通过expose来控制父组件可以访问子组件那些的方法和对象,我们将通过和option api(选项式 api)来演示父组件如何调用子组件的方法。
vue2 选项式API
<template>
<!-- 子组件 -->
<TestComponent ref="TestComponent"></TestComponent>
</template>
<script>
// 导入子组件
import TestComponent from './TestComponent'
export default {
components: {
TestComponent
},
mounted () {
// 调用子组件方法
this.$refs.TestComponent.show()
}
}
</script>
//详细版 vue2 选项式API 实现 父组件调用子组件方法
<!-- 父组件 app.vue -->
<template>
<div class="itxst">
<!-- 使用 ref 命令 -->
<child ref="childComp"/>
<button @click="onClick">点击试一试</button>
</div>
</template>
<script >
import child from "./child.vue";
export default {
name: "app",
//注册组件
components: {
child,
},
methods: {
onClick: function () {
//获取到 子组件的 数据
let msg = this.$refs.childComp.message;
//执行了子组件的 play方法
this.$refs.childComp.play();
},
},
};
</script>
<!-- 子组件 child.vue -->
<template>
<div class="itxst">
{{ title }}
</div>
</template>
<script>
//选项式默认当前实例是全部暴露
export default {
name: "demo",
//默认全部暴露 也可以通过expose控制那些需要暴露
//expose: ['play'],
data() {
return {
title: "www.itxst.com",
};
},
methods: {
play: function () {
this.title = "你调用了子组件的方法";
},
},
};
</script>