文章总结:介绍了两种实现父组件触发子组件方法的常用方法:通过ref访问子组件实例并调用方法,以及使用自定义事件触发子组件方法
目录
1 通过 ref 取得子组件实例并调用方法2 使用自定义事件总结有多种方法可以实现父组件触发子组件中的方法,以下是其中两种常用的方法:
1 通过 ref 取得子组件实例并调用方法
父组件可以在模板中通过 ref 给子组件命名,然后在父组件中使用 $refs 访问子组件实例的方法。
<!-- 父组件 --><template> <div> <button @click="callChildMethod">调用子组件方法</button> <child-component ref="child"></child-component> </div></template><script>import ChildComponent from './ChildComponent.vue'export default { components: { ChildComponent }, methods: { callChildMethod() {this.$refs.child.childMethod();//不传参this.$refs.child.childMethodParam(param);//可以直接向子组件传递参数param } }}</script>
在子组件中,需要在 methods 中定义要被调用的 childMethod 方法。
<!-- 子组件 --><template> <div> <!-- 组件内容 --> </div></template><script>export default { methods: { childMethod() { console.log('子组件方法被调用') },childMethodParam(param) { console.log('子组件方法被调用,并接收到父组件传递过来的参数:',param) } }}</script>
2 使用自定义事件
父组件可以在需要触发子组件中的方法的时候,通过 $emit 触发自定义事件。然后在子组件中监听该事件,在事件回调函数中执行对应的方法。
<!-- 父组件 --><template> <div> <button @click="callChildMethod">调用子组件方法</button> <child-component @custom-event="onCustomEvent"></child-component> </div></template><script>import ChildComponent from './ChildComponent.vue'export default { components: { ChildComponent }, methods: { callChildMethod() { this.$emit('custom-event') }, onCustomEvent() { console.log('custom-event 事件被触发') } }}</script>
在子组件中,需要通过 props 来接收父组件传递的自定义事件,并在 created 生命周期中对其进行监听。
<!-- 子组件 --><template> <div> <!-- 组件内容 --> </div></template><script>export default { props: ['customEvent'], created() { this.$on('custom-event', this.childMethod) }, methods: { childMethod() { console.log('子组件方法被调用') } }}</script>