父组件中怎么调用子组件的方法。要求整体内容的风格为:尽量简单直接一点
可以通过在父组件中使用ref来获取子组件实例,然后再调用子组件的方法。具体步骤如下:
- 在子组件上添加ref属性,例如:
<ChildComponent ref="child"></ChildComponent>
- 在父组件中使用$refs来获取子组件实例,例如:
this.$refs.child
- 通过获取的子组件实例来调用子组件中的方法,例如:
this.$refs.child.method()
其中,method()为子组件中需要调用的方法名。
完整示例代码如下:
<!-- 子组件 -->
<template>
<div>{{message}}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello World'
}
},
methods: {
showMessage() {
alert(this.message)
}
}
}
</script>
<!-- 父组件 -->
<template>
<div>
<ChildComponent ref="child"></ChildComponent>
<button @click="handleClick">调用子组件方法</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
methods: {
handleClick() {
this.$refs.child.showMessage()
}
}
}
</script>
原文地址: https://www.cveoy.top/t/topic/bah6 著作权归作者所有。请勿转载和采集!