要触发子组件的事件,可以使用$refs来获取子组件实例,然后调用其方法。具体步骤如下:
-
在父组件中,给子组件添加ref属性,以便在父组件中获取子组件实例。
-
在父组件中使用this.$refs获取子组件实例,并调用子组件的方法。
例如,在父组件中可通过以下方式来调用子组件的一个名为foo的方法:
// 父组件
<template>
<div>
<child-component ref="child"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
triggerChildMethod() {
this.$refs.child.foo();
}
}
}
</script>
// 子组件
<template>
<div>
子组件内容
</div>
</template>
<script>
export default {
methods: {
foo() {
console.log('子组件方法被调用');
}
}
}
</script>