vue2父组件自动调用子组件方法
时间: 2023-10-13 08:29:06 浏览: 86
在 Vue2 中,父组件可以通过 `ref` 属性获取到子组件实例,并且调用子组件的方法。具体步骤如下:
1. 在子组件标签上添加 `ref` 属性,如 `<child ref="child"></child>`。
2. 在父组件中使用 `$refs` 获取子组件实例,如 `this.$refs.child`。
3. 调用子组件的方法,如 `this.$refs.child.methodName()`。
示例代码如下:
子组件:
```
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, World!'
}
},
methods: {
showMessage() {
alert(this.message)
}
}
}
</script>
```
父组件:
```
<template>
<div>
<child ref="child"></child>
<button @click="showChildMessage">Show Child Message</button>
</div>
</template>
<script>
import Child from './Child.vue'
export default {
components: {
Child
},
methods: {
showChildMessage() {
this.$refs.child.showMessage()
}
}
}
</script>
```
在上面的例子中,点击按钮会弹出子组件中的 message 值。注意,在调用子组件方法之前,需要确保子组件已经被渲染并且能够被找到,否则会报错。
阅读全文