父组件获取子组件中的dom元素
时间: 2023-11-25 19:06:07 浏览: 33
父组件获取子组件中的DOM元素可以通过refs实现。具体步骤如下:
1.在子组件中给需要获取的DOM元素添加ref属性。
2.在父组件中通过this.$refs获取子组件的DOM元素。
下面是一个Vue的例子:
```html
<!-- 子组件 -->
<template>
<div>
<input type="text" ref="input">
</div>
</template>
<script>
export default {
name: 'ChildComponent',
// ...
}
</script>
<!-- 父组件 -->
<template>
<div>
<ChildComponent ref="child"></ChildComponent>
<button @click="handleClick">获取子组件input的值</button>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
name: 'ParentComponent',
components: {
ChildComponent
},
methods: {
handleClick() {
console.log(this.$refs.child.$refs.input.value)
}
}
}
</script>
```
在上面的例子中,子组件中的input元素添加了ref="input"属性,父组件中通过ref="child"获取子组件的实例,然后通过this.$refs.child.$refs.input获取子组件中的input元素,并输出其value值。